Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for multiple row actions in a SQL Server trigger?

My kindergarten SQL Server taught me that a trigger may be fired with multiple rows in the inserted and deleted pseudo tables. I mostly write my trigger code with this in mind, often resulting in some cursor based cludge. Now I'm really only able to test them firing for a single row at a time. How can I generate a multirow trigger and will SQL Server actually ever send a multirow trigger? Can I set a flag so that SQL Server will only fire single row triggers??

like image 613
Tom Avatar asked Jan 02 '09 20:01

Tom


People also ask

How do I test Triggers in SQL?

To test Trigger, we need to execute the SQL query embedded in the trigger independently first and record the result. Then execute the trigger as whole and Compare the results. Triggers are useful for enforcing business rules, validating input data, and keeping an audit trail etc.

What is the order of execution if we have multiple Triggers for the same event on the same table?

SQL Server allows multiple triggers on the table for the same event and there is no defined order of execution of these triggers. We can set the order of a trigger to either first or last using procedure sp_settriggerorder. There can be only one first or last trigger for each statement on a table.

How do you tell if SQL trigger is firing?

To test if a trigger fires you can add a PRINT statement to the trigger (e.g. "PRINT 'trigger fired!' "), then do something that should trigger the trigger. If you get the printed text in your messages-tab in management studio you know it fired.


2 Answers

Trigger definitions should always handle multiple rows.

Taken from SQLTeam:

-- BAD Trigger code following:

CREATE TRIGGER trg_Table1 
ON Table1 
For UPDATE
AS
DECLARE @var1 int, @var2 varchar(50)

SELECT @var1 = Table1_ID, @var2 = Column2
FROM inserted

UPDATE Table2
SET SomeColumn = @var2
WHERE Table1_ID = @var1

The above trigger will only work for the last row in the inserted table.

This is how you should implement it:

CREATE TRIGGER trg_Table1 
ON Table1 
FOR UPDATE
AS

UPDATE t2
SET SomeColumn = i.SomeColumn
FROM Table2 t2
INNER JOIN inserted i
ON t2.Table1_ID = i.Table1_ID
like image 66
Mitch Wheat Avatar answered Nov 03 '22 21:11

Mitch Wheat


Yes, if a statement affects more than one row, it should be handled by a single trigger call, as you might want to revert the whole transaction. It is not possible to split it to separate trigger calls logically and I don't think SQL Server provides such a flag. You can make SQL Server call your trigger with multiple rows by issuing an UPDATE or DELETE statement that affects multiple rows.

like image 32
mmx Avatar answered Nov 03 '22 22:11

mmx