SQL Server Is there a way to dynamically paste values to table in sql

vd2z7a6w  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(139)

I have a 3 tables in my database. They are

Table_1

Table_2

General_table

select * from General_table

id  Col1 
1   34
2   35
9   34

I have written a dynamic query where in I need to extract contents in Table_1 and Table_2. So

declare @fil nvarchar(max) = '34'
declare @new_var nvarchar(max) 

set @new_var = 'select id from General_table where col1 =' + ''''+@fil+''''

print('select * from Table_'+@new_var+'')

When I execute this, I get below output

But the expected output is to be dynamically calling Table_1

Expected output

select * from Table_1

Similarly, when I pass @fil as 35, the expected output should be

select * from Table_2
wfypjpf4

wfypjpf41#

Does the following snippet help build the SQL String you are expecting?

declare @sql NVarchar(max), @fil Int = 34;

select @sql = Concat(N'Select * from Table_', Id)
from General_Table
where col1 = @fil;

print @sql;
/* exec sp_executesql @sql; */

相关问题