SQL Server 2005 - 触发不触发

时间:2011-08-01 14:41:33

标签: sql-server

我有两张桌子User&用户日志。用户日志表基本上记录了对用户表所做的所有更改(插入/更新/删除)。

我在User表上有一个触发器,如下所示:

ALTER TRIGGER [dbo].[TRG_UserLog]
   ON  [dbo].[Users]
   FOR INSERT,UPDATE,DELETE
AS 
-- Declare variables here
DECLARE @UserName  VARCHAR(50)
DECLARE @FirstName  VARCHAR(50)
DECLARE @LastName       VARCHAR(50)
DECLARE @Email  VARCHAR(50)
DECLARE @RoleID   INT
DECLARE @UpdatedBy VARCHAR(50)

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here

    IF @@ROWCOUNT = 0
    BEGIN
        RETURN
    END


    IF EXISTS(SELECT * FROM INSERTED)
        --INSERTED / UPDATED
        BEGIN
                SET @UserName   = ( SELECT UserName FROM INSERTED)
                SET @FirstName  = ( SELECT FirstName FROM INSERTED)
                SET @LastName   = ( SELECT LastName FROM INSERTED)
                SET @Email      = ( SELECT Email FROM INSERTED)
                SET @RoleID     = ( SELECT RoleID FROM INSERTED) 
                SET @UpdatedBy  = ( SELECT ModifiedBy FROM INSERTED)
                INSERT INTO UserLog(UserName,FirstName,LastName,Email,RoleID,[DateTime],UpdatedBy)
                    VALUES (@UserName,@FirstName,@LastName,@Email,@RoleID,GETDATE(),@UpdatedBy)
        END
    ELSE
        -- DELETED
        BEGIN
                SET @UserName   = ( SELECT UserName FROM DELETED)
                SET @FirstName  = ( SELECT FirstName FROM DELETED)
                SET @LastName   = ( SELECT LastName FROM DELETED)
                SET @Email      = ( SELECT Email FROM DELETED)
                SET @RoleID     = ( SELECT RoleID FROM DELETED) 
                SET @UpdatedBy  = ( SELECT ModifiedBy FROM DELETED)
                INSERT INTO UserLog(UserName,FirstName,LastName,Email,RoleID,[DateTime],UpdatedBy)
                    VALUES (@UserName,@FirstName,@LastName,@Email,@RoleID,GETDATE(),@UpdatedBy)
        END
END

当对用户表进行插入/更新或删除时,上面的triigger不会在userlog表中插入数据。代码有什么问题吗?

2 个答案:

答案 0 :(得分:5)

您不应该从INSERTED和DELETED设置变量。这些“表”可能会在其中包含多于一行,并且使用set将丢失数据。这样做(在INSERT和DELETE块上):

INSERT INTO UserLog(UserName, FirstName, LastName, Email, RoleID, [DateTime], UpdatedBy)
SELECT UserName, FirstName, LastName, Email, RoleID, getdate(), ModifiedBy
FROM INSERTED

如果进行了更改,则甚至不需要IF / ELSE块,因为它只会根据这些表中是否有行来INSERT / DELETE。

此外,不需要检查@@ ROWCOUNT。你应该能够完全删除它。

答案 1 :(得分:2)

这将永远是真的:

SET NOCOUNT ON;   -- this sets @@ROWCOUNT to 0

IF @@ROWCOUNT = 0
BEGIN
    RETURN
END

因为调用SET NOCOUNT ON;会影响@@ROWCOUNT,并且由于该语句不会影响任何行,所以它被设置为0.因此其余代码永远不会运行。至少,您可以在SET NOCOUNT ON;之前运行该代码(或将@@ROWCOUNT存储在变量中供以后使用),但正如另一个答案所示,无论如何都是完全没有必要的。