Handling multiple rows in SQL Server trigger

前端 未结 3 2091
一向
一向 2020-12-19 03:00

We have a database with a table called WarehouseItem where product\'s stock levels are kept. I need to know when ever this table get\'s updated, so I create

3条回答
  •  难免孤独
    2020-12-19 03:44

    in case of the trigger is for INSERT, UPDATE this code will exit the trigger IF Records are being updated AND more than one record is being afftected:

    IF (SELECT COUNT(*) FROM Deleted) > 1
      BEGIN
         Return
      END
    

    But if you wish to examin every record in the INSERTED recordset you can use this method:

       DECLARE rstAST CURSOR FOR
       SELECT ins.TaskActionId,
              _Task.CustomerId,
              _AST.ASTQRId,
              ins.ExistingQRcode,
              ins.NewQRcode
              FROM Inserted ins INNER JOIN
                   dbo.cdn_AST _AST ON ins.ASTId = _AST.ASTId INNER JOIN
                   dbo.tsk_Task _Task ON ins.TaskId = _Task.TaskId
    
        OPEN rstAST
        FETCH NEXT FROM rstAST INTO @TaskActionId, @TaskCustomerId, @ASTQRId, @ExistingQRcode, @NewQRcode
        WHILE @@FETCH_STATUS = 0
        BEGIN
          --use CONTINUE to skip next record or let it traverse the loop
    
          FETCH NEXT FROM rstAST INTO @TaskActionId, @TaskCustomerId, @ASTQRId, @ExistingQRcode, @NewQRcode
        END
        CLOSE rstAST
        DEALLOCATE rstAST
    

提交回复
热议问题