I\'ve created this stored procedure which dynamically creates the same trigger for all my tables:
USE [MyDatabase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIE
1) EXEC[UTE]
can execute only T-SQL statements.
GO
is not T-SQL statement.
GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server.
2) You could replace
SET @SQL = '
--Drop Trigger
BEGIN TRY
DROP TRIGGER [dbo].[TR_' + @TableName + '_Audit]
END TRY
BEGIN CATCH
END CATCH
GO
--Create Trigger
CREATE TRIGGER [dbo].[TR_' + @TableName + '_Audit]
with
DECLARE @TriggerName SYSNAME;
SET @TriggerName = 'TR_' + @TableName + '_Audit';
IF EXISTS (
SELECT *
FROM sys.triggers
WHERE parent_id = OBJECT_ID(@TableName)
AND name = @TriggerName
)
BEGIN
SET @SQL = N'DROP TRIGGER [dbo].' + QUOTENAME(@TriggerName);
EXEC(@SQL);
END
SET @SQL = '
--Create Trigger
CREATE TRIGGER [dbo].[TR_' + @TableName + '_Audit]
or (better)
with
DECLARE @TriggerName SYSNAME;
SET @TriggerName = 'TR_' + @TableName + '_Audit';
IF NOT EXISTS (
SELECT *
FROM sys.triggers
WHERE parent_id = OBJECT_ID(@TableName)
AND name = @TriggerName
)
BEGIN
SET @SQL = N'CREATE TRIGGER [dbo].' + QUOTENAME(@TriggerName) + 'ON ' + @TableName + ' AFTER INSERT, UPDATE, DELETE AS BEGIN SELECT NULL END';
EXEC(@SQL);
END
SET @SQL = '
--Alter Trigger
ALTER TRIGGER [dbo].[TR_' + @TableName + '_Audit]
Note: The object's name should be NVARCHAR(128)
or SYSNAME
.