SQL Server A trigger to work on multiple row inserts

后端 未结 3 1885
难免孤独
难免孤独 2020-12-01 13:35

I am maintaining some code that has a trigger on a table to increment a column. That column is then used by a 3rd party application A. Lets say that the table is ca

相关标签:
3条回答
  • 2020-12-01 13:41

    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?

    0 讨论(0)
  • 2020-12-01 13:42

    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;
    
    0 讨论(0)
  • 2020-12-01 13:49

    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?

    0 讨论(0)
提交回复
热议问题