SQL Server A trigger to work on multiple row inserts
Solution 1:
You just have to open a cursor on INSERTED and iterate it for @PROC_NEWNUM1 and put your rest of code that loop. e.g
DECLARE @PROC_NEWNUM1 VARCHAR (10)
DECLARE @NEWNUM2 numeric(20)
DECLARE my_Cursor CURSOR FOR SELECT num1 FROM INSERTED;
OPEN my_Cursor;
FETCH NEXT FROM @PROC_NEWNUM1;
WHILE @@FETCH_STATUS = 0
BEGIN FETCH NEXT FROM my_Cursor
select @NEWNUM2 = MAX(num2) from TEST
if @NEWNUM2 is null
Begin
set @NEWNUM2 = 0
end
set @NEWNUM2 = @NEWNUM2 + 1
UPDATE TEST SET num2 = @NEWNUM2 WHERE num1 = @PROC_NEWNUM1
END;
CLOSE my_Cursor; DEALLOCATE my_Cursor;
Solution 2:
Take a look at inserted
pseudo table in your trigger as it will contain multiple rows during these operations. You should always handle multiple rows in your triggers anyway.
See here for more info:
How to test for multiple row actions in a SQL Server trigger?
Solution 3:
Trigger needs to be rewriteen to handle multiple row inserts. Never write a trigger like that using variables. All triggers must alawys consider that someday someone is going to do a multi-row insert/update/delete.
You shouldn't be incrementing columns that way in a trigger either, if you need incremented column numbers why aren't you using an identity column?