views:

55

answers:

3

In a trigger, I have code like:

SET @var1 = (SELECT col1 FROM Inserted);
SET @var2 = (SELECT col2 FROM Inserted);

Is it possible to write the above in a single line? Something conceptually like:

SET (@var1,@var2) = (SELECT col1,col2 FROM Inserted);

Obviously I tried the above, without success; am I just stuck with the first method?

Even if possible, is that a good idea?

Thanks!

+6  A: 

yes, use first method.

Or...

SELECT
    @var1 = col1
    ,@var2 = col2
FROM
    Inserted;
gbn
A: 

No, it is not possible. SET accepts a single target and value. AFAIK.

Sky Sanders
+1  A: 

However, it is a major red flag if you are expecting to set variable values like that in a trigger. It generally means the trigger is poorly designed and needs revision. This code expects there will be only one record in inserted and this is something that is not going to be true in all cases. A multiple record insert or update will have multiple records in inserted and the trigger must account for that (please without using a trigger!!!). Triggers should under no circumstances be written to handle only one-record inserts/updates or deletes. They must be written to handle sets of data.

Example to insert the values from inserted to another table where the trigger is on table1:

CREATE TRIGGER mytrigger on table1
AFTER INSERT
AS

INSERT table2 (field1, field2, field3)
SELECT field1, 'test', CASE WHEN field3 >10 THEN field3 ELSE 0 END
FROM inserted
HLGEM
Would you have an example I can look at for multiple record insert trigger?Thanks.
johansson
I see, thanks. So how would I handle that in a trigger?
johansson
That is the sample trigger, not sure I understand what you are asking for now.
HLGEM
Sorry. I understand you're inserting to table2 with values from the inserts to table2.What I mean, how do I handle each record in Inserted checking values for each column? For example, if a trigger had multiple CardTransaction, I need to analyze each CardTransaction in Inserted.Is that clearer or need I post more?
johansson
YOu handle them inthe select statment. Post what your current trigger is doing in the questions and I can try to show you how to make it set-based.
HLGEM
Oh, what about a cursor that goes through each record in Inserted?
johansson