[英]ASP.Net: How I can check whether a row already exists in the database?
I want to check whether a value already exists in my database or not - if it exists then I will use an update query, otherwise I will perform an insert. 我想检查数据库中是否已经存在一个值-如果存在,那么我将使用更新查询,否则将执行插入操作。
How should I do this? 我应该怎么做?
just select the row by passing the value. 只需通过传递值来选择行。 If the returned rowcount>o means there is a value in the table.
如果返回的rowcount> o表示表中有一个值。 In that case update it otherwise insert into table.
在这种情况下,将其更新,否则将其插入表中。
You could write a Stored-Procedure that checks whether that unique field already exists or not. 您可以编写一个存储过程,以检查该唯一字段是否已经存在。 One approach would be to use the SP only for inserts and check there if the value already exists.
一种方法是仅将SP用于插入,并在那里检查该值是否已存在。 If it returns yes, you could call the Update-StoredProcedure.
如果返回yes,则可以调用Update-StoredProcedure。 That approach is fail-safe.
该方法是故障安全的。
Another approach would be to update directly in the "Insert"-SP when it has detect that the value exists. 另一种方法是在检测到该值存在时直接在“ Insert” -SP中进行更新。 In my opinion this is obfuscated code.
我认为这是混淆的代码。
IF (EXISTS (SELECT *
FROM YourTable
WHERE LoweredUniqueField = LOWER(@Value)))
BEGIN
-- you could use this output parameter as information
SET @InfoCode = 1
GOTO Cleanup
END
-- Else Insert new record:
INSERT INTO .....
Cleanup:
RETURN @InfoCode
END
I think that your question is not asp-specific and I'm assuming you're connecting to an MS SQL SERVER. 我认为您的问题不是特定于ASP的,并且我假设您正在连接到MS SQL SERVER。
Let's say you have a simple table like this: 假设您有一个简单的表格,如下所示:
CREATE TABLE Products_table ( [ProductID] [int] NULL, [Qty] [int] NULL ) ON [PRIMARY]
If you want to update the Qty of a given product when it exists, otherwise create it, you could use the following statement: 如果要在给定产品存在时更新其数量,否则要创建它,则可以使用以下语句:
UPDATE Products_table SET Qty = 1000 WHERE ProductID = 10
INSERT INTO Products_table (ProductID,Qty)
SELECT 10 as ProductID, 1000 as ProductQty
WHERE NOT EXISTS (SELECT 1 FROM Products_table WHERE ProductID = 10 )
Update would work only if there is a ProductID = 10, and Insert will create a new row only if it doesn't already exist. 仅当ProductID = 10时更新才有效,并且插入将仅在不存在的情况下创建新行。 You should put both statements as a query in a single SqlCommand and execute it.
您应该将两个语句作为查询放在单个SqlCommand中,然后执行它。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.