| Author |
Topic |
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-14 : 10:42:57
|
In order to resolve a problem I created a new table to get the data I need. Can I use a single trigger to Insert, Update and Delete the new table whenever another table is changed? I need a trigger that will Insert, Update or Delete on table load_pounds_detail. I created a new table like this and got all the records for the table for a start:Set NoCount OnCreate load_pounds_detail(ticket_number_detail varchar(10), pickup_date_detail datetime, load_pounds_detail int)Insert into load_pounds_detail Select Distinct ticket_number, pickup_date, load_poundsIf Exists(Select * From load_pounds_detail Group by ticket_number_detail , pickup_date_detailHaving Sum(1)>1)Begin ReturnEnd if it can all be done with one trigger would someone provide an example.If table detail_record (changes for any reason) table load_pounds_detail will reflect those changes.Thanks for the helpCoachBarker |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2009-03-14 : 10:46:07
|
Like this:CREATE TRIGGER trg_name ON tableAFTER INSERT,UPDATE,DELETEASBEGINIF EXISTS (SELECT * FROM INSERTED)AND NOT EXISTS(SELECT * FROM DELETED)BEGININSERT INTO table2SELECT your fields FROM INSERTED iENDIF EXISTS (SELECT * FROM INSERTED)AND EXISTS(SELECT * FROM DELETED)BEGINUPDATE tSET t.field1=i.field1,t.field2=i.field2,...FROM table2 tINNER JOIN INSERTED iON i.FKCol=t.PKColENDIF NOT EXISTS (SELECT * FROM INSERTED)AND EXISTS(SELECT * FROM DELETED)BEGINDELETE t FROM table2 tINNER JOIN DELETED dON d.FKCol=t.PKColEND |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-14 : 10:51:29
|
| Wow, the response time in here is great. I will give it a try and post back any questions or issues that I have.Thanks for the helpCoachBarker |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-16 : 12:13:47
|
| what do the i and the t signify?Thanks for the helpCoachBarker |
 |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-03-16 : 12:49:44
|
| >>what do the i and the t signify?they are table aliasesBe One with the OptimizerTG |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-16 : 12:57:06
|
So then if I have IF NOT EXISTS (SELECT * FROM INSERTED)AND EXISTS(SELECT * FROM DELETED)BEGINDELETE t FROM table2 tINNER JOIN DELETED dON d.FKCol=t.PKColEND I should end up with :IF NOT EXISTS (SELECT * FROM INSERTED)AND EXISTS(SELECT * FROM DELETED)BEGINDELETE ticket_number FROM detail_record.ticket_numberINNER JOIN DELETED dON detail_record.ticket_number=load_pound_detail.ticket_numberEND Thanks for the helpCoachBarker |
 |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-03-16 : 13:07:21
|
| Not sure what you mean by "if I have...I should end up with".sql will resolve the aliases internally so you can create and use table aliases for ease of typing and for read-ability. So as long as you define the alias when you list the table you can then refer to the columns as <alias>.<columnName>. The "FKCol" and "PKCol" was something you need to replace (as you did) with the actual column names.Be One with the OptimizerTG |
 |
|
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2009-03-16 : 13:15:38
|
quote: I should end up with :IF NOT EXISTS (SELECT * FROM INSERTED)AND EXISTS(SELECT * FROM DELETED)BEGINDELETE ticket_number FROM detail_record.ticket_numberINNER JOIN DELETED dON detail_record.ticket_number=load_pound_detail.ticket_numberEND
Not quite -- you haven't quite got the idea of the table alias in your DELETE statement.DELETE deletes all the data in 1 or more rows in a table -- you can't pass it a column name which you are trying to do here. I think what you want to do is this:IF NOT EXISTS (SELECT * FROM INSERTED) AND EXISTS(SELECT * FROM DELETED) BEGIN DELETE r FROM detail_record r INNER JOIN DELETED d ON r.[ticket_number] = d.[ticket_number]END You can see that there is an alias (r) for the detail_record tables and an alias (d) for the virtual table DELETED. Then you use the DELETED table as you would any other table and JOIN by its alias.Does this help?Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-16 : 13:23:36
|
Is there a way to do an insert like this?IF EXISTS (SELECT * FROM INSERTED)AND NOT EXISTS(SELECT * FROM DELETED)BEGININSERT INTO adjust_load_poundsSELECT DISTINCT detail_record.ticket_number, detail_record.pickup_dt, detail_record.ddp_weightFROM INSERTED END I got this as an error:quote: Msg 4104, Level 16, State 1, Procedure trg_adjust_load_pounds, Line 14The multi-part identifier "detail_record.ticket_number" could not be bound.Msg 4104, Level 16, State 1, Procedure trg_adjust_load_pounds, Line 14The multi-part identifier "detail_record.pickup_dt" could not be bound.Msg 4104, Level 16, State 1, Procedure trg_adjust_load_pounds, Line 14The multi-part identifier "detail_record.ddp_weight" could not be bound.
Thanks for the helpCoachBarker |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-16 : 13:41:08
|
quote: Originally posted by CoachBarker Is there a way to do an insert like this?IF EXISTS (SELECT * FROM INSERTED)AND NOT EXISTS(SELECT * FROM DELETED)BEGININSERT INTO adjust_load_poundsSELECT DISTINCT detail_record.ticket_number, detail_record.pickup_dt, detail_record.ddp_weightFROM INSERTED END I got this as an error:quote: Msg 4104, Level 16, State 1, Procedure trg_adjust_load_pounds, Line 14The multi-part identifier "detail_record.ticket_number" could not be bound.Msg 4104, Level 16, State 1, Procedure trg_adjust_load_pounds, Line 14The multi-part identifier "detail_record.pickup_dt" could not be bound.Msg 4104, Level 16, State 1, Procedure trg_adjust_load_pounds, Line 14The multi-part identifier "detail_record.ddp_weight" could not be bound.
Thanks for the helpCoachBarker
you've used alias without defining it. in this case since you've a single table alias is not at all required. this is enoughIF EXISTS (SELECT * FROM INSERTED)AND NOT EXISTS(SELECT * FROM DELETED)BEGININSERT INTO adjust_load_poundsSELECT DISTINCT ticket_number, pickup_dt, ddp_weightFROM INSERTED END |
 |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-03-16 : 13:50:02
|
| As you know, He actually wasn't using an alias with that statement he was using the actual table name. The O.P. is not only confused about aliases they also don't really know the fundamentals of SELECT/FROM clauses. I think it's important for the O.P. to understand that the reason your statement will work, Visakh, is because with only one table listed in the FROM clause there can be no ambiguity about which table a given column is from. The statement could be more specificly written as this:SELECT DISTINCT INSERTED.ticket_number, INSERTED.pickup_dt, INSERTED.ddp_weightFROM INSERTED Which should also make it more obvious why their previous statement error'd out.Be One with the OptimizerTG |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-16 : 14:19:29
|
| You better believe the OP is confused at times, I am trying to learn all of this on the fly, using SQL Server and SSRS. Not a lot of help around here. I do understand alias's, I had just never seen them like that before. Unfortunately the only way to learn this quickly is to get assistance from those on the web who know what they are doing. I was hired on as a .net programmer and knew i would be getting into some other areas.Didn't see the post by TransactCharlie, so then those are legitimate alias's that sql wil acknowledge?Thanks for the helpCoachBarker |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-16 : 14:34:39
|
| You can start learning about this from books online. it has illustrations for most of cases. you can easily learn from samples given |
 |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-03-16 : 14:51:42
|
Keep the faith, Coach! Win one for the gipper and all that . And as Visakh suggested (when you get some time) work though the sub-topics and samples here: Query Fundamentalshttp://technet.microsoft.com/en-us/library/ms190659(SQL.90).aspxAnd get used to looking at the actual t-sql reference topics. that has been my best resource.Be One with the OptimizerTG |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-16 : 15:04:50
|
| I'll try to squeeze in, between the work and the family life there is only so many hours. They are hiring(IT) here, you think they would hire soemone with some SQL and SSQS skills, at least then there would be someone in house to go to. You can only learn so much on-line and it can be a time waster too.Thanks for the helpCoachBarker |
 |
|
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2009-03-17 : 05:32:39
|
I've found the help and support here to be nothing but excellent all round. If you are still a bit unsure of using aliases then here is a little example -- you can run this in any query analyser window -- no permanent tables will be touched. For more information I can't recommend this site enough -- you will get responses but if you've done your best to get as far as you can first you'll get better responses!the alias examples:-- Make up a table variable to show UPDATE / SELECT / DELETE ops on-- Table varialbes *must* be referenced via an alias-- They cannot be referenced directly except in the most simple caseDECLARE @foo TABLE ( [Id] INT IDENTITY (1,1) PRIMARY KEY , [valA] VARCHAR(50) , [valB] MONEY )-- Table varialbe @bar -- the fooId will be a link to @foo-- in a base table you'd enforce this with a foreign key.DECLARE @bar TABLE ( [fooId] INT , [val] DATETIME )-- Populate the @foo Table-- Alias(s) are useless for inserts they always use proper namesINSERT INTO @foo ( [valA] , [valB] ) SELECT 'a', 100UNION SELECT 'b', 200UNION SELECT 'c', 300UNION SELECT 'd', 400-- Populate the @bar tableINSERT INTO @bar ( [fooID] , [val] ) SELECT 1, '2009-01-01T23:59:59'UNION SELECT 2, '2007-06-04T12:00:00'UNION SELECT 3, '2009-04-01T00:00:00'-- Show the @foo Table (note here not using an alias)SELECT '@foo after INSERTS', * FROM @foo ORDER BY [valA] ASC-- Show the @bar Table (using an alias -- you would never want to do this for real)-- The AS keyword can also be used betweent he alias and the table, it's not needed and most-- people leave it out. You tend to see the AS more in derived tables.-- Both these SELECT statements are the sameSELECT '@bar Alias No AS', b.[fooID], b.[val] FROM @bar bSELECT '@bar Alias using AS', b.[fooId], b.[val] FROM @bar AS b-- SELECT example using LEFT JOIN and aliases-- I tend to use the AS keyword when changing the returned column names in the result set-- Example -- from f.[ID] to [fooId]-- but I never use the AS keywords for aliases (this is just personal preference though)SELECT 'LEFT JOIN @Bar Example' , f.[Id] AS [FooId] , b.[val] AS [Effective Date] , f.[valb] AS [Cost]FROM @foo f -- Going to LEFT JOIN @bar here on @bar.[fooId] = @foo.[Id] -- Because these are table variables we can't actually do that without aliases LEFT JOIN @bar b ON b.[fooId] = f.[Id]-- UPDATE example using aliases (show the @foo table before and after)-- This updates @foo valA column to 'X' and valb column to 0 where the corrospnding @Bar-- data is in 2009SELECT 'Before UPDATE', * FROM @fooUPDATE f SET [valA] = 'X' , [valB] = 000.00FROM @foo f JOIN @bar b ON b.[fooId] = f.[ID]WHERE b.[val] >= '2009-01-01T00:00:00' AND b.[val] < '2010-01-01T00:00:00'SELECT 'After UPDATE', * FROM @foo-- DELETE example using aliases (show the @foo table before and after)-- We are going to delete every row in @foo that does not have a corrosponding entry in @bar-- Remember that the WHERE clause is evaluated AFTER the JOINS have been resolved.SELECT 'Before DELETE', * FROM @fooDELETE fFROM @foo f LEFT JOIN @bar b ON b.[fooId] = f.[Id]WHERE b.[fooId] IS NULLSELECT 'After DELETE', * FROM @foo Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION |
 |
|
|
CoachBarker
Posting Yak Master
170 Posts |
Posted - 2009-03-17 : 06:18:26
|
Oh I agree about the help and support in this forum, and many others that I visit. Nothing but first rate, unfortunately while in school we only touched creating the most basic of queries snd SPROC (basic insert, delete, select and update). And being more of a programmer, I usually only had to worry about writing the code to use the SPROC or the query, not actually writing the query itself. So now it is time to start learning over again. Thanks for the helpCoachBarker |
 |
|
|
|