I have the following t-sql code which generates an error
Declare @table TABLE
(
ID1 int,
ID2 int
)
INSERT INTO @table values(1, 1);
INSERT INTO @table values(2, 2);
INSERT INTO @table values(3, 3);
DECLARE @field varchar(50);
SET @field = 'ID1'
DECLARE @query varchar(MAX);
SET @query = 'SELECT * FROM @table WHERE ' + @field + ' = 1'
EXEC (@query)
The error is Must declare the table variable "@table".
What's wrong with the query. How to fix it?
You cannot use the EXEC statement or the sp_executesql stored procedure to run a dynamic SQL Server query that refers a table variable, if the table variable was created outside the EXEC statement or the sp_executesql stored procedure. Because table variables can be referenced in their local scope only, an EXEC statement and a sp_executesql stored procedure would be outside the scope of the table variable. However, you can create the table variable and perform all processing inside the EXEC statement or the sp_executesql stored procedure because then the table variables local scope is in the EXEC statement or the sp_executesql stored procedure.
Try this may work for you: