2013-03-26 34 views
0

我想在表上插入時使用觸發器,但由於錯誤我無法創建它。在T-SQL中編寫基本的觸發器

-- ================================================ 
-- 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和欄目有:

  • AuditID PK
  • 用戶名
  • 的moduleId
  • LoggedInDate

觸發我想創建的是我創建的表TblAuditLogLoggingIn。但管理工作室說它不存在?

+0

上是否存在TblAuditLogLoggingIn用戶名? – 2013-03-26 09:52:14

+0

該表屬於哪個模式? – ChrisBint 2013-03-26 09:52:27

+0

查看我更新的帖子,查找您的問題的答案。 – 2013-03-26 10:02:44

回答

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滿足一些條件,空例如,那麼你可以做這樣的事情:

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