我有以下要在数据库中的每个表上执行的触发器:
EXECUTE sp_MSforeachtable @command1 =
'IF EXISTS (SELECT * FROM sys.triggers
WHERE Object_ID = Object_ID("Insert_Serverdate_Into_CreatedAt"))
DROP TRIGGER Insert_Serverdate_Into_CreatedAt
GO
CREATE TRIGGER Insert_Serverdate_Into_CreatedAt ON ?
AFTER INSERT
AS
BEGIN
INSERT INTO ? (CreatedAt) VALUES(GETDATE())
END
GO
IF EXISTS (SELECT * FROM sys.triggers
WHERE Object_ID = Object_ID("Insert_Serverdate_Into_UpdatedAt"))
DROP TRIGGER Insert_Serverdate_Into_UpdatedAt
GO
CREATE TRIGGER Insert_Serverdate_Into_UpdatedAt ON ?
AFTER UPDATE
AS
BEGIN
INSERT INTO ? (UpdatedAt) VALUES(GETDATE())
END
GO'
我收到每个表的以下错误:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'GO'.
Msg 111, Level 15, State 1, Line 6
'CREATE TRIGGER' must be the first statement in a query batch.
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near 'GO'.
Msg 102, Level 15, State 1, Line 17
Incorrect syntax near 'GO'.
Msg 102, Level 15, State 1, Line 25
当我在一个表上尝试没有 MSforeachtable 过程的触发器时,它可以工作。有人知道上面的查询有什么问题吗?
谢谢
编辑:
我什至试图将这两个语句分成两个命令并DROP TRIGGER
省略。如果它不存在就创建它。现在我发现关键字附近的语法不正确TRIGGER