代码之家  ›  专栏  ›  技术社区  ›  KuldipMCA

在没有循环的情况下插入或更新?

  •  0
  • KuldipMCA  · 技术社区  · 14 年前

    我的表有两列:

    ItemMaster (Item INT, Quantity INT)
    

    2 回复  |  直到 14 年前
        1
  •  4
  •   Codesleuth    14 年前

    无需循环即可完成是:

    UPDATE table1
    SET Quantity = Quantity + 1
    WHERE Item = @itemID
    
    IF @@ROWCOUNT = 0
        INSERT INTO table1 (Item, Quantity)
        VALUES (@itemID, 1)
    
        2
  •  1
  •   Michael Pakhantsov    14 年前

     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