开发者

upsert with addition

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)


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜