使用存储过程创建触发器

时间:2012-02-21 01:22:04

标签: sql ms-access stored-procedures triggers

我有一个触发器,我想从存储过程中启动它。我正在使用ms访问,当我从ms访问运行触发器时,它给我一个错误消息(ODBC)。我想我无法使用ms访问创建触发器。这是我的触发器:

IF EXISTS 
(SELECT name 
FROM sys.objects 
WHERE name = 'UpdateComments' AND type = 'TR')
DROP TRIGGER tblEmailHdr_abenit01.UpdateComments; 
GO 
CREATE TRIGGER UpdateComments 
ON tblEmailHdr_abenit01 
AFTER Update 
AS 
IF ( UPDATE (Comments) ) BEGIN Update ttblEmailHdr_abenit01 
Set UpdateComm = GetDate() 
END;
GO

这就是我尝试从存储过程创建触发器的方法,但是当我尝试创建sproc时,我收到以下错误信息:

Sproc:

CREATE PROCEDURE dbo.SP_AS_tblEmailHdr_Trig (@UserID as varchar(10)) 
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 --SET NOCOUNT ON;

-- Insert statements for procedure here
 Declare @UserTable Varchar(50)
 Declare @UserTable2 Varchar(50)

 Set @UserTable = 'tblEmailHdr_' + @UserID ;
 Set @UserTable2 = 'tblEmailHdr_' + @UserID + '.UpdateComments' ;

IF EXISTS 
 (SELECT name 
 FROM sys.objects 
 WHERE name = 'UpdateComments' AND type = 'TR') DROP TRIGGER @UserTable2   

 GO
 CREATE TRIGGER UpdateComments 
 ON @UserTable 
 AFTER UPDATE 
 AS 
 IF ( UPDATE (Comments) )
 BEGIN
  --RAISERROR (50009, 16, 10)
  Update @UserTable 
  Set UpdatedComm = GetDate() 
 END
 GO

END

GO

错误消息我得到:

Msg 102, Level 15, State 1, Procedure SP_AS_tblEmailHdr_Trig, Line 23
Incorrect syntax near '@UserTable2'.
Msg 102, Level 15, State 1, Procedure UpdateComments, Line 2
Incorrect syntax near '@UserTable'.
Msg 1087, Level 15, State 2, Procedure UpdateComments, Line 8
Must declare the table variable "@UserTable".
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'END'.

2 个答案:

答案 0 :(得分:0)

create procedure pro (parameters)
as
begin
  declare @trigs nvarchar(max)
  declare @trip nvarchar(max)
  set @trigs='
    create trigger tri on dbo.employee
    for insert
    as
      select * from inserted
    go'
  set @trip='drop trigger tri'

  EXEC sp_executeSQL @trigs

  insert into employee values(parameters)

  EXEC sp_executeSQL @trip
end

exec pro param
eg:
exec pro 80,'aaa','AAS',25000,'2013-02-01','iT'

答案 1 :(得分:-1)

从过程中删除所有GO语句。