2015/02/24

SQL Tigger 如何區分Insert, Update, Delete

ALTER TRIGGER [dbo].[TRI_TableName]
     ON  [dbo].[TableName]
     AFTER INSERT,DELETE,UPDATE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @action as char(1);
 SET @action = 'I'; -- Set Action to Insert by default.

 IF EXISTS(SELECT * FROM DELETED)
    BEGIN
        SET @action =
            CASE
                WHEN EXISTS(SELECT * FROM INSERTED) THEN 'U' -- Set Action to Updated.
                ELSE 'D' -- Set Action to Deleted.      
            END
    END


if @action = 'I'
     begin
         -- 新增 Insert
     end

if @action = 'U'
     begin
         -- 修改 Update
     end

if @action = 'D'
     begin
         -- 刪除 Delete
     end

END

沒有留言:

張貼留言