Procedure If exists update else insert in table with SQL Server composite key

1

Hello.

I want to synchronize a table with the Linked Server, however the problem is that the table has composite primary key, and I do not know how to do the check to fetch the record. Can someone please help me?!

Thank you!

    
asked by anonymous 09.04.2015 / 17:45

1 answer

1

In this way I will show you the integrity of the data with the use of the transaction, see if this helps you:

begin tran
if exists (select * from Sua_tabela with (updlock,serializable) where key1 = @key1 and key2 = @key2)
begin
   update Sua_tabela set ...
   where key1 = @key1 and key2 = @key2
end
else
begin
insert Sua_tabela (key1, key2 ...)
values (@key1, @key2, ...)
end
commit tran

or

begin tran
   update Sua_tabela with (serializable) set ...
   where key = @key and key2 = @key2

   if @@rowcount = 0
   begin
      insert Sua_tabela (key1, key2, ...) values (@key1, @key2, ...)
   end
commit tran
    
14.09.2015 / 18:25