Skip to content
Advertisement

SQL does not recognize tablename from select statement

If I write the tablename after ‘FROM’ the query works. If I use the result of a select statement the query does not resolve. Is there a workaround?

I have tried resolving the tablename as an output from a stored procedure but I cannot seem to use exec in a stored procedure or function without receiving an error

Incorrect syntax near keyword where

Advertisement

Answer

As I stated in my comment “That isn’t how SQL works. You can’t replace an object with an expression, variable name, etc. It has to be a ltieral; you need to use parametrised dynamic SQL.”. I believe this does what you’re after.

I build a dynamic statement, and put that into @SQL; along with ensuring I properly quote the dynamic object name, using QUOTENAME. Then I build the parameters and pass them all to the dynamic statement us sp_executesql.

If you get stuck, uncomment your best friend (and comment out the EXEC) and debug the printed SQL.

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