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 |
|
jmiller
Starting Member
7 Posts |
Posted - 2007-01-31 : 12:28:44
|
I need help on a trigger that will update a tables value if the skew number is exists, if not, add it to the table. My information is below, I have tried many triggers, but all without results I am looking for. I just need a little help thinking outside the box. tbl_invskew(nvarchar)cases(int)skids(int)tbl_enterid(int)skew(nvarchar)cases(int)skids(int)date(date)Basically, When a record is inserted into tbl_enter it will fire a trigger that inserts skew(nvarchar),cases(int),skids(int) into tbl_inv. If skew already exists in tbl_inv it will add the inserted data to the current data.Example:Before Data inserted into tbl_entertbl_invFCA6850-01 50 7528113-26000P 25 50FCA4939-01 75 100Inserted data into tbl_enterFCA6850-01 10 20After Data inserted into tbl_enter and trigger firestbl_invFCA6850-01 60 9528113-26000P 25 50FCA4939-01 75 100But if the skew does not exists in the table it just adds it in. Example:Before Data inserted into tbl_enterFCA6850-01 50 7528113-26000P 25 50FCA4939-01 75 100Inserted data into tbl_enterZZZZZ-01 15 20After Data inserted into tbl_enter and trigger firesFCA6850-01 60 9528113-26000P 25 50FCA4939-01 75 100ZZZZZ-01 15 20This is what I think the trigger should look like, but wrongCREATE TRIGGER [skew_inv] ON tbl_enterFOR INSERTASINSERT tbl_inv (skew,cases,skids)Select skew,+cases,+skidsFrom insertedwhere skew=i.skew |
|
|
sshelper
Posting Yak Master
216 Posts |
Posted - 2007-01-31 : 12:38:00
|
| Try this trigger:CREATE TRIGGER [skew_inv] ON tbl_enterFOR INSERTAS-- Step #1 : Insert all Skews that doesn't exist, with cases and skids set to 0INSERT tbl_inv (skew,cases,skids)Select skew, 0, 0From inserted IWHERE NOT EXISTS (SELECT 'X' FROM tbl_inv Inv WHERE I.Skew = Inv.Skew)-- Step #2 : Add the Cases and SkidsUPDATE ASET Cases = Cases + B.Cases, Skids = Skids + B.SkidsFROM tbl_inv A INNER JOIN inserted B ON A.skew = B.skewSQL Server Helperhttp://www.sql-server-helper.com |
 |
|
|
|
|
|
|
|