Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Trigger with ExecuteSqlCommand() Throws "Incorrect syntax near the word 'TRIGGER'."

This seems like I'm missing a simple detail, I just can't figure out what.

Having this

string deleteTrigger =
            "IF OBJECT_ID('@p0') IS NOT NULL " +
            "DROP TRIGGER [@p1] ";
string createTrigger = 
            "CREATE TRIGGER [@p0] " +
            "ON [dbo].[@p1] " +
            "AFTER DELETE AS " +
            "BEGIN " +
                "SET NoCount ON " +
                "DELETE FROM [dbo].[MyTable] WHERE ID IN (SELECT ID FROM DELETED) " +
            "END ";

object[] parameterList = new object[] {"Tr_SomeTable_AD", "Tr_SomeTable_AD" };
context.Database.ExecuteSqlCommand(deleteTrigger,parameterList); // Works
parameterList = new object[] { "Tr_SomeTable_AD", "SomeTable" };
context.Database.ExecuteSqlCommand(createTrigger, parameterList); // Exception thrown here!

in my InitializeDatabase(DbContext) throws an exception:

SqlException: Incorrect syntax near the word 'TRIGGER'

on the second ExecuteSqlCommand (the first one works fine). I've also tried

context.Database.ExecuteSqlCommand(createTrigger, "Tr_SomeTable_AD", "SomeTable");

instead of using an object[], but the result is the same.

I saw this question, but the answer does not solve my problem. I know the problem must be related to the fact that I'm using parameters, because if I just put the values in the createTrigger string, the SQL command works. However, I'd like to have it parameterized to make it easier to use the same trigger creation code on different tables.

SOLUTION:

As said by @marc_s (see answer below), I cannot parametrize table or column (or trigger) names in T-SQL - I'll have to create the complete, final T-SQL statement in C# (using string.Format()). Thus:

string deleteTrigger = "..."; // same as before
string createTrigger = 
            "CREATE TRIGGER [dbo].[{0}] " + 
            "ON [dbo].[{1}] " + ...

object[] parameterList = new object[] {"Tr_SomeTable_AD", "Tr_SomeTable_AD" };
context.Database.ExecuteSqlCommand(string.Format(deleteTrigger,parameterList)); 
parameterList = new object[] { "Tr_SomeTable_AD", "SomeTable" }; // Use string.Format() here!
context.Database.ExecuteSqlCommand(string.Format(createTrigger, parameterList));

does the trick.

like image 431
user1987392 Avatar asked Feb 03 '26 23:02

user1987392


1 Answers

You cannot parametrize table or column (or trigger) names in T-SQL; unfortunately, DDL (Data Definition Language) statements cannot be parametrized.

You will have to create the complete, final T-SQL statement in C# (using string.Format()) and then execute that completed T-SQL statement as a whole.

like image 58
marc_s Avatar answered Feb 06 '26 15:02

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!