有没有一种动态将数值粘贴到SQL表中的方法?

huangapple go评论69阅读模式
英文:

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+'')

当我执行这个查询时,我得到了以下输出

有没有一种动态将数值粘贴到SQL表中的方法?

但是预期的输出应该是动态调用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

有没有一种动态将数值粘贴到SQL表中的方法?

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; */

huangapple
  • 本文由 发表于 2023年6月16日 00:51:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定