How can I use a table variable while executing a command string?
DECLARE @FileIDs TABLE
(
File_ID int
)
insert into @FileIDs select ID from Files where Name like '%bla%';
DECLARE @testquery as varchar(max);
set @testquery = 'select * from @FileIDs';
exec(@testquery);
returns the following error
Msg 1087, Level 15, State 2, Line 1 Must declare the table variable "@FileIDs".
Table variable is a type of local variable that used to store data temporarily, similar to the temp table in SQL Server. Tempdb database is used to store table variables. To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign.
Temp table: A Temp table is easy to create and back up data. Table variable: But the table variable involves the effort when we usually create the normal tables. Temp table: Temp table result can be used by multiple users. Table variable: But the table variable can be used by the current user only.
We can define a table variable inside a stored procedure and function as well. In this case, the table variable scope is within the stored procedure and function. We cannot use it outside the scope of the batch, stored procedure or function.
You can use a table variable with dynamic SQL, but you must declare the table inside the dynamic SQL itself.
The table @FileIDs
is not in the scope of exec(@testquery)
.
That's why you have that problem.
To solve this problem you may use a temporary table
:
CREATE table #FileIDs
(
File_ID int
)
insert into #FileIDs select ID from Files where Name like '%bla%';
DECLARE @testquery as varchar(max);
set @testquery = 'select * from #FileIDs';
exec(@testquery);
drop table #FileIDs
or put the table in the scope:
DECLARE @sql nvarchar(2000)
SET @sql='DECLARE @FileIDs TABLE ( File_ID int);'
SET @sql=@sql+'insert into @FileIDs select ID from Files where Name like ''%bla%'';'
set @sql=@sql+ 'select * from @FileIDs;'
EXECUTE sp_executesql @sql
Indeed table is out of the scope, try this:
DECLARE @sql nvarchar(2000)
SET @sql='DECLARE @FileIDs TABLE ( File_ID int);'
SET @sql=@sql+'insert into @FileIDs select ID from Files where Name like ''%bla%'';'
set @sql=@sql+ 'select * from @FileIDs;'
EXECUTE sp_executesql @sql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With