0

When I run the below code, it runs and prints the SQL output perfectly.

However the last EXEC statement throws an error

Incorrect syntax near the keyword 'TRIGGER'

The code basically strings together some SQL to create a trigger for all existing tables.

When I manually take that PRINT output at the end and execute it in SSMS it works fine, but the EXEC in the code just won't run it.

DECLARE @sql AS NVARCHAR(MAX)
SET @sql = ''

SELECT @sql = @sql + 'CREATE TRIGGER [tr_' + table_name +'] ON 
[' + table_schema + '].[' + table_name + '] FOR INSERT, UPDATE, DELETE AS
SELECT 1 GO' + CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.TABLES
WHERE table_type = 'BASE TABLE'

PRINT @sql; -- output is correct and I can paste this and it works
EXEC sp_executesql @sql -- doesn't work
2
  • 1
    You could try to replace the GO with a semicolon (surrounded by a space before and after) ` ; ` and see if that works Commented Feb 13, 2015 at 13:57
  • Ok I'll bite and ask the big white elephant in the room. Why are you adding a trigger to every single table in your database? Triggers should be used very sparingly, like a few in your entire career. Commented Feb 13, 2015 at 15:15

1 Answer 1

2

The SQL command to execute has to be a single batch. So, you can't use GO.

You better declare a CURSOR and execute the script for each table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.