As part of some administrative tasks, we have many tables that each need a trigger created. The trigger will set a flag and the date in the Audit database when an object has
If you use SSMS (or other similar tool) to run the code produced by this script, you will get exactly the same error. It could run all right when you inserted batch delimiters (GO
), but now that you don't, you'll face the same issue in SSMS too.
On the other hand, the reason why you cannot put GO
in your dynamic scripts is because GO
isn't a SQL statement, it's merely a delimiter recognised by SSMS and some other tools. Probably you are already aware of that.
Anyway, the point of GO
is for the tool to know that the code should be split and its parts run separately. And that, separately, is what you should do in your code as well.
So, you have these options:
insert EXEC sp_execute @sql
just after the part that drops the trigger, then reset the value of @sql
to then store and run the definition part in its turn;
use two variables, @sql1
and @sql2
, store the IF EXISTS/DROP part into @sql1
, the CREATE TRIGGER one into @sql2
, then run both scripts (again, separately).
But then, as you've already found out, you'll face another issue: you cannot create a trigger in another database without running the statement in the context of that database.
Now, there are 2 ways of providing the necessary context:
1) use a USE
statement;
2) run the statement(s) as a dynamic query using EXEC targetdatabase..sp_executesql N'…'
.
Obviously, the first option isn't going to work here: we cannot add USE …
before CREATE TRIGGER
, because the latter must be the only statement in the batch.
The second option can be used, but it will require an additional layer of dynamicity (not sure if it's a word). It's because the database name is a parameter here and so we need to run EXEC targetdatabase..sp_executesql N'…'
as a dynamic script, and since the actual script to run is itself supposed to be a dynamic script, it, therefore, will be nested twice.
So, before the (second) EXEC sp_executesql @sql;
line add the following:
SET @sql = N'EXEC ' + @dbname + '..sp_executesql N'''
+ REPLACE(@sql, '''', '''''') + '''';
As you can see, to integrate the contents of @sql
as a nested dynamic script properly, they must be enclosed in single quotes. For the same reason, every single quotation mark in @sql
must be doubled (e.g. using the REPLACE() function, as in the above statement).
a trigger creation must be done on its own execution batch. You are inside a procedure so you wont be able to create it.
I suggest adding the @sql into a temp table and then once the proc is finish generating all of the statements, loop this temp table to execute them and create the triggers