简体   繁体   中英

Using table variable with dynamic fields as input for dynamic SQL

I want to use a table in a dynamic query. But columns of table are not fixed and they may change.

declare @t table(ID int, Fname varchar(50), Lname varchar(50)); -- Columns may change
insert into @t(ID, Fname, Lname)
values
(1, 'Jack', 'Martinez'),
(2, 'Alex', 'Desoza');

I have tried below code:

declare @tablename nvarchar(max) = '@t'
declare @query nvarchar(max) = 'select * from '+ @tablename 
exec sp_executesql @query 

But the only thing I get is :

Must declare the scalar variable "@t".

You need to bring the definition of your table variable into 'dynamic' part of the code:

declare @query nvarchar(max) = '
declare @t table(ID int, Fname varchar(50), Lname varchar(50));
insert into @t(ID, Fname, Lname)
values
(1, ''Jack'', ''Martinez''),
(2, ''Alex'', ''Desoza'');
select * from @t' 
exec sp_executesql @query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM