加法更新插入

发布于 2024-09-03 02:36:19 字数 230 浏览 4 评论 0原文

在 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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我不会写诗 2024-09-10 02:36:19
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
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
回眸一笑 2024-09-10 02:36:19

据我所知,使用 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文