Procedure If exists update Else Insert in table with composite SQL Server key

Asked

Viewed 376 times

1

Hello.

I want to synchronize a table with Linked Server, but the problem is that the table has a composite primary key, and I don’t know how to check to find the record. Can someone please help me?!

Thank you!

1 answer

1

This way I’ll show you guarantees the integrity of the data with the use of the transaction, see if it 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.