Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table variable and exec

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".

like image 295
alex555 Avatar asked Jul 06 '12 10:07

alex555


People also ask

What is a table variable?

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.

What is #temp table and @table variable in SQL Server?

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.

Can we use table variable in function?

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.

Can we use table variable in dynamic query?

You can use a table variable with dynamic SQL, but you must declare the table inside the dynamic SQL itself.


2 Answers

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
like image 135
aF. Avatar answered Sep 18 '22 20:09

aF.


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
like image 37
David Aleu Avatar answered Sep 19 '22 20:09

David Aleu