英文:
Is there a way to dynamically paste values to table in sql
问题
我数据库中有3张表。它们是:
Table_1
Table_2
General_table
select * from General_table
id Col1
1 34
2 35
9 34
我编写了一个动态查询,在其中需要提取Table_1和Table_2中的内容。
所以
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+'')
当我执行这个查询时,我得到了以下输出
但是预期的输出应该是动态调用Table_1
预期输出
select * from Table_1
类似地,当我将@fil设置为35时,预期的输出应该是
select * from Table_2
英文:
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
答案1
得分: 1
以下是翻译好的部分:
是否以下代码片段有助于构建您期望的 SQL 字符串?
声明 @sql NVarchar(max),@fil Int = 34;
从 General_Table 中选择 @sql = Concat(N'Select * from Table_', Id)
where col1 = @fil;
打印 @sql;
/* 执行 sp_executesql @sql; */
英文:
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; */
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论