sql-serversql-server-2008visual-studio-2010insert-updateon-duplicate-key

How to insert a new row to a table only if when same value does not exist, else update the related contents?


Table:

emergency_tab (user_id, emergency_no)

and

Constraints (user_id [primary key])

When id and no are received, I'm required to insert those values to user_id and emergency_no columns in the emergency_tab. And if there exist a column with same user_id, I just wanted to update the emergency_no only, no need to insert new row.

I'm using Visual Studio 2010 and MS SQL Server 2008 inbuilt in vs10


Solution

  • It is working

     IF (SELECT COUNT(*) FROM emergency_tab WHERE user_id='?')<>0
        BEGIN
             --UPDATE
        END 
    
    ELSE    
         BEGIN
           --INSERT
         END