View Single Post
  #8 (permalink)  
Old 05-30-2007, 06:57 AM
Unregistered
 
Posts: n/a
Default ANY answer. Re: Insert or update a record if it already exists?

Quote:
Originally Posted by Rob137 View Post
How about this:
[sql]
if (exists (select * from AA_TestTable as t1
where t1.ord_num = 'FFF'))
begin
update AA_TestTable
set ord_qty = 999
where ord_num = 'FFF'
end
else
begin
insert into AA_TestTable (ord_num, top_assy, ord_qty)
values('GGG', 'XYZ', 567)
end
[/sql]
(I assume there is a typo in the last statement, where ord_num should be set to 'FFF').

You should be VERY CAREFUL with things like this. If you can't afford to set the transaction isolation level to SERIALIZABLE, some other transaction could add the row with ord_num='FFF' after you've tested for its existence, but before you've inserted it. This way you end up with violated primary constraint and error in one of these transactions.
Reply With Quote