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

牧云@^-^@ 提交于 2019-12-11 09:42:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26675464/creating-a-trigger-with-executesqlcommand-throws-incorrect-syntax-near-the-wo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!