在T-SQL中编写基本触发器

时间:2013-03-26 09:50:48

标签: sql-server tsql triggers

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

   -- ================================================
-- 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

错误是:

  

Msg 8197,Level 16,State 4,Procedure ModuleID,Line 6       对象'TblAuditLogLoggingIn.UserID'不存在或对此操作无效。

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

  • AuditID PK
  • UserID
  • ModuleID
  • LoggedInDate

我试图创建的触发器是我创建的表TblAuditLogLoggingIn。但管理工作室表示它不存在?

1 个答案:

答案 0 :(得分: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