views:

25

answers:

2

How would you write the following in Microsoft SQL Server 2008?

IF EXISTS(SELECT * FROM Table WHERE Something=1000)
UPDATE Table SET Qty = Qty + 1 WHERE Something=1000
ELSE
INSERT INTO Table(Something,Qty) VALUES(1000,1)
+4  A: 
IF EXISTS(SELECT * FROM Table WHERE Something=1000)
BEGIN
 UPDATE Table SET Qty = Qty + 1 WHERE Something=1000
END
ELSE
BEGIN
 INSERT INTO Table(Something,Qty) VALUES(1000,1)
END
Developer Art
+1  A: 

Using the new merge command in SQL Server 2008 would as far as I can gather be:

merge Table t
using (select 1000 as Something, 1 as Qty) s on t.Something = s.Something
when matched then
  update set t.Qty = t.Qty + 1
when not matched by target then
  insert values (s.Something, s.Qty);

That not so simple, as the merge is more efficient for merging bigger sets, not just a single record. Otherwise you can just attempt to update the record, and insert one if no records were updated:

update Table set Qty = Qty + 1 where Something = 1000
if (@@rowcount = 0) begin
  insert into Table (Something, Qty) values (1000, 1)
end
Guffa
I like your second solution. Very tight. I even took off the begin and end.
cf_PhillipSenn

related questions