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