开发者

ASP.Net: How I can check whether a row already exists in the database?

开发者 https://www.devze.com 2023-02-26 11:48 出处:网络
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开发者_JAVA百科.

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开发者_JAVA百科.

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. 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. If it returns yes, you could call the 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. 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.

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. You should put both statements as a query in a single SqlCommand and execute it.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号