您将如何在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)
答案 0 :(得分:4)
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
答案 1 :(得分:3)
在SQL Server 2008中使用新的merge
命令,我可以收集到:
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);
这不是那么简单,因为合并对于合并更大的集合更有效,而不仅仅是单个记录。否则,您可以尝试更新记录,如果没有更新记录,则插入一个记录:
update Table set Qty = Qty + 1 where Something = 1000
if (@@rowcount = 0) begin
insert into Table (Something, Qty) values (1000, 1)
end