Skip to content
Advertisement

Eror While Executing a dynamic queries in a variable

I’m executing a dynamic query from a variable but it always says:

Could not find stored procedure

I have tried to use simpler queries like set @query = 'select * from [table_name]' but it gives the same error.

In my temporary table is the list of all my trigger name so the expected output I want to get is Command(s) completed successfully. Not ‘Could not find stored procedure’, because I supposed to executing a dynamic queries not a stored procedure.

Advertisement

Answer

Instead EXEC @query use, EXEC sp_executesql @query. From the docs:

Executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically. The Transact-SQL statement or batch can contain embedded parameters.

Or if you want to use EXEC, change it to:

From the documentation you have:

Execute a character string { EXEC | EXECUTE }
( { @string_variable | [ N ]’tsql_string’ } [ + …n ] )
[ AS { LOGIN | USER } = ‘ name ‘ ] [;]

which means your @string_variable or string must be wrapped in ().

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement