views:

59

answers:

2

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.

+4  A: 

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)
Codesleuth
You are right but for your answer i have to use the loop of all the item and process one by one item than it is possible.
KuldipMCA
My answer doesn't involve any loops. You might need to edit your question if there's another requirement here somewhere.
Codesleuth
yes but for that you have to use IN clause like that WHERE ITEMID IN (Select ItemID from ITEMMASTER)
KuldipMCA
@KuldipMCA you're commenting on the wrong answer.
Codesleuth
+1  A: 

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 
Michael Pakhantsov