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 |
|
Lora Brown
Starting Member
2 Posts |
Posted - 2011-12-13 : 13:39:22
|
| Suppose I have 2 tables. Store(Table1) has a column ItemQty and Sales(Table2) has a column QtySold. When data inserted in Qtysold column of Sales table, the ItemQty column of Store Table will be updated with a value which is =(ItemQty - QtySold) Now I want to create a trigger which will update this new data in Store table.Note :- 1. The ItemId(PK) in Store table is ItemId(FK)in Sales table.2.QtySold should always less than ItemQty.Please help soon.Thanks |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-12-13 : 13:44:01
|
| [code]CREATE TRIGGER StockUpdON SalesFOR INSERTASBEGIN UPDATE sSET s.ItemQty = s.ItemQty -i.QtySoldFROM Store sINNER JOIN (SELECT ItemId,SUM(QtySold) AS QtySold FROM INSERTED GROUP BY ItemId)iON i.ItemId = s.ItemIdEND[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
sunnyleoneo
Starting Member
19 Posts |
Posted - 2011-12-13 : 14:19:36
|
| You can create after insert on your 2nd table. In that you can write update to your first table by joining with inserted table of sql server. Following is pseudo code. please check is there any syntax error. Hope this will work.CREATE TRIGGER trigname ON Sales AFTER INSERTASUPDATE store set itemqty = itemqty - inserted.qtysoldinner join inserted on table1.itemid = inserted.itemidGO |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-12-13 : 23:38:52
|
quote: Originally posted by sunnyleoneo You can create after insert on your 2nd table. In that you can write update to your first table by joining with inserted table of sql server. Following is pseudo code. please check is there any syntax error. Hope this will work.CREATE TRIGGER trigname ON Sales AFTER INSERTASUPDATE store set itemqty = itemqty - inserted.qtysoldinner join inserted on table1.itemid = inserted.itemidGO
please check the code before postingthe above is not syntactically correct------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2011-12-14 : 09:38:14
|
| I think trigger should allow for UPDATE?? |
 |
|
|
Lora Brown
Starting Member
2 Posts |
Posted - 2011-12-15 : 12:10:35
|
| Thanks a lot Vishkha....It works perfectly for me. Thank you again, appreciated. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-12-15 : 12:13:35
|
| wc------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|