Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
FrumpleOrz
Starting Member
2 Posts |
Posted - 2011-06-26 : 16:12:19
|
| Hi there, sorry if this has been asked before. I'm pretty new to the SQL stuff.I've got a table of stock levels and whenever I get new inventory I want to be able to add it to the current table. I was wondering if there was a way to have so if an item already exists in the table, it will just add to the available quantity but if it can't find the record, it will append the table with the new item.For example, I have a table like this:ItemNumber QuantityApples 3Oranges 2Pears 0and the new inventory I have looks like this:ItemNumber QuantityApples 1Peaches 2Pears 1and I want the end result to look like this:ItemNumber QuantityApples 4Oranges 2Pears 1Peaches 2Is there a simple way to get these results? Thanks in advance. |
|
|
FrumpleOrz
Starting Member
2 Posts |
Posted - 2011-06-26 : 20:05:47
|
| Okay, I ended up using the following piece of code. Can anyone see any sort of problem the following could cause?insert into Inventory (ItemNumber, Quantity)SelectItemnumberTest,NewItems.quantityfromInventoryright join newitems on inventory.ItemNumber = newitems.itemnumbertestwhere Inventory.ItemNumber is nullgoupdate Inventoryset Inventory.quantity = (Inventory.Quantity + newitems.quantity)fromInventoryleft join newitems on inventory.ItemNumber = newitems.itemnumbertestwhere NewItems.ItemNumberTest is not nullgodelete from NewItemsedit: Ha. I see an issue already. I'm adding the new items after I've added the rows, so it'll double the quantity of the new item. Okay, so if I switch the order of the queries there, can anyone see another issue? |
 |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2011-06-26 : 21:44:14
|
I would do the update first, and then do the inserts (and then delete everything from newitems table)update Inventory set Inventory.quantity = (Inventory.Quantity + newitems.quantity)from Inventory inner join newitems on inventory.ItemNumber = newitems.itemnumbertestwhere NewItems.ItemNumberTest is not null; -- the where clause may not be required.insert into Inventoryselect ItemnumberTest,NewItems.quantityfrom newitemswhere not exists ( select * from Inventory where Inventory.ItemNumber = newitems.ItemnumberTest );truncate table newitmes; You may want to wrap all the statements in a transaction and a try/catch block (if you are on SQL 2005 or higher). |
 |
|
|
|
|
|
|
|