0

我想在对表进行插入时使用触发器,但由于错误而无法创建它。

   -- ================================================
-- Template generated from Template Explorer using:
-- Create Trigger (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- See additional Create Trigger templates for more
-- examples of different Trigger statements.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Nick Gowdy
-- Create date: 26/03/2013
-- Description: Insert Module ID into table based on User ID on update
-- =============================================
CREATE TRIGGER TblAuditLogLoggingIn.ModuleID ON dbo.GenesisOnline.TblAuditLogLoggingIn.UserID
AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here

END
GO

错误是:

消息 8197,级别 16,状态 4,过程 ModuleID,第 6 行对象“TblAuditLogLoggingIn.UserID”不存在或对于此操作无效。

架构是 dbo.GenesisOnline.TblAuditLogLoggingIn,列是:

  • 审计ID PK
  • 用户身份
  • 模块ID
  • 登录日期

我要创建的触发器是针对我创建的表 TblAuditLogLoggingIn 的。但管理工作室说它不存在?

4

1 回答 1

2

好的,感谢您澄清您的问题@nick gowdy。首先,SQL Server 不接受带有点 (.)的名称。然后,如前面的答案所述,您不能以这种方式基于列创建触发器。如果您想对触发器上的列进行操作,您应该这样做:

CREATE TRIGGER TblAuditLogLoggingIn_ModuleID ON dbo.GenesisOnline
AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    IF ( UPDATE(UserID) )
    BEGIN
        -- do your stuff here
    END
END
GO

但这几乎肯定会导致do your stuff here一直被执行。do your stuff如果您要做的是UserID满足某些条件,例如 null ,那么您可以执行以下操作:

DECLARE @UserID int --assuming that is the type of your UserID
SELECT @UserID = UserID from inserted
IF ( @UserID is null ) -- change this to a criteria appropriate to your code
BEGIN
    -- do your stuff here
END
于 2013-03-26T11:46:43.583 回答