Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force a trigger to run on an update statement with multiple rows?

Tags:

sql

sql-server

I have had to make changes to a trigger and assumed that running an update query like the following would make the trigger execute for all the matched rows. But instead, it only updates the record that it finds.

UPDATE someTable SET someField = someField WHERE someField = 'something';

As a quick solution, I created the following query using a cursor to loop through the records and update each row. It works, and luckily I don't have a really large dataset so it doens't take too long, but it just doesn't seem like the best solution.

DECLARE @id INT;
DECLARE queryCursor CURSOR FOR 
SELECT id FROM someTable WHERE someField='something'

OPEN queryCursor
FETCH NEXT FROM queryCursor INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN 
 UPDATE someTable SET someField = someField WHERE id = @id
 FETCH NEXT FROM queryCursor INTO @id
END

CLOSE queryCursor
DEALLOCATE queryCursor

Is there a better way to get a trigger to execute on multiple rows in SQL Server?

Edit: The code from trigger

FOR INSERT, UPDATE
AS
IF UPDATE (LineNumber)
OR UPDATE(LineService)

Begin

DECLARE @CDL VARCHAR(50)
DECLARE @LN VARCHAR(100)
DECLARE @A  VARCHAR(25)

SELECT @CDL = CommonDataLink FROM INSERTED
SELECT @A = LineService FROM INSERTED

SET @LN = @CDL + @A

UPDATE CommonData SET ReportedLineNo = @LN WHERE CommonDataLink = @CDL

End
like image 846
xecaps12 Avatar asked Jul 17 '26 20:07

xecaps12


1 Answers

You have to make use of the special table INSERTED for what you want:

UPDATED CODE

FOR INSERT, UPDATE
AS
IF UPDATE (LineNumber)
OR UPDATE(LineService)

Begin

DECLARE @CDL VARCHAR(50)
DECLARE @LN VARCHAR(100)
DECLARE @A  VARCHAR(25)

SELECT @CDL = CommonDataLink FROM INSERTED
SELECT @A = LineService FROM INSERTED

SET @LN = @CDL + @A

UPDATE A
SET ReportedLineNo = B.LineService + B.CommonDataLink
FROM CommonData A
INNER JOIN INSERTED B
ON A.CommonDataLink = B.CommonDataLink 


End
like image 118
Lamak Avatar answered Jul 19 '26 12:07

Lamak