不循环插入或更新?

发布于 2024-09-14 11:57:19 字数 177 浏览 3 评论 0原文

我有一个包含两列的表格:

ItemMaster (Item INT, Quantity INT)

如果一个项目已经存在,那么我应该更新数量。否则,我必须在此表中插入一条记录。

没有循环这可能吗?

我正在使用 SQL Server 2005。

I have table with two columns:

ItemMaster (Item INT, Quantity INT)

If an item is already there, then I should update the Quantity. Otherwise, I have to insert a Record in this table.

Is this possible without Loop?

I'm using SQL Server 2005.

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

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

发布评论

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

评论(2

梦途 2024-09-21 11:57:19

它可以在没有循环的情况下完成,是的:

UPDATE table1
SET Quantity = Quantity + 1
WHERE Item = @itemID

IF @@ROWCOUNT = 0
    INSERT INTO table1 (Item, Quantity)
    VALUES (@itemID, 1)

It can be done without a loop yes:

UPDATE table1
SET Quantity = Quantity + 1
WHERE Item = @itemID

IF @@ROWCOUNT = 0
    INSERT INTO table1 (Item, Quantity)
    VALUES (@itemID, 1)
心奴独伤 2024-09-21 11:57:19

对于一行

 IF EXISTS (SELECT * from ItemMaster WHERE Item = @Item)
    UPDATE ItemMaster
      SET Quantity = @Quantity
    WHERE Item = @Item
 ELSE
    INSERT INTO ItemMaster VALUES(@Item, @Quantity)

对于多行:

 INSERT INTO ItemMaster (Item, Quantity)
 SELECT Item, Quantity
 FROM AnotherTable a
 WHERE NOT EXISTS (Select 1 from ItemMaster i Where i.Item = a.Item);

 UPDATE ItemMaster i
    SET Quantity = a.Quantity
 FROM AnotherTable a
 WHERE a.Item = i.Item 

FOR one row

 IF EXISTS (SELECT * from ItemMaster WHERE Item = @Item)
    UPDATE ItemMaster
      SET Quantity = @Quantity
    WHERE Item = @Item
 ELSE
    INSERT INTO ItemMaster VALUES(@Item, @Quantity)

For many rows:

 INSERT INTO ItemMaster (Item, Quantity)
 SELECT Item, Quantity
 FROM AnotherTable a
 WHERE NOT EXISTS (Select 1 from ItemMaster i Where i.Item = a.Item);

 UPDATE ItemMaster i
    SET Quantity = a.Quantity
 FROM AnotherTable a
 WHERE a.Item = i.Item 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文