【问题标题】:Insert or Update without a loop?插入或更新没有循环?
【发布时间】:2010-08-18 08:08:32
【问题描述】:

我有两列的表格:

ItemMaster (Item INT, Quantity INT)

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

如果没有循环,这可能吗?

我使用的是 SQL Server 2005。

【问题讨论】:

  • 一种可能性来纠正 2 个不同的查询。

标签: sql sql-server-2005 stored-procedures insert-update


【解决方案1】:

可以不用循环是的:

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

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

【讨论】:

  • 您是对的,但是对于您的答案,我必须使用所有项目的循环并逐项处理。
  • 我的回答不涉及任何循环。如果这里有其他要求,您可能需要编辑您的问题。
  • 是的,但为此您必须使用 IN 子句,如 WHERE ITEMID IN (Select ItemID from ITEMMASTER)
【解决方案2】:

一排

 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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2015-09-11
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多