繁体   English   中英

从表中选择作为列名给出的记录。 动态SQL

[英]select records from table given as column name. Dynamic sql

我在这里搜索了一些主题,但是没有任何需要的答案。 我想进行查询,在哪里我将基于第一个表中的列名加入一个表。

我正在使用sql server,因此如果有人知道该技术的解决方案,将不胜感激。

这是我想做的一个示例:

桌子

main_table
----------
id | tab      | another_col
----------------------
1 | product_x | abcd
2 | product_y | efgh


table_product_x
----------------------
id | yyy
----------------------
1 | simple_yyy_value1


table_product_y
----------------------
id | yyy
----------------------
2 | simple_yyy_value4

输出

product_x | simple_yyy_value1 | abcd
product_y | simple_yyy_value4 | efgh

查询草图

select tab, yyy, another_col from main_table
join 'table_'+tab xxx on xxx.id = main_table.id

您可以使用union all和一些动态SQL来构建它。

declare @SQL nvarchar(max)
declare @Pattern nvarchar(100)

set @Pattern = 'select ''[TABLE_NAME]'' as TableName, yyy from table_[TABLE_NAME]'

select @SQL = stuff((select ' union all '+replace(@Pattern, '[TABLE_NAME]', tab)
                     from main_table
                     for xml path(''), type).value('.', 'nvarchar(max)'), 1, 11, '')

exec (@SQL)

执行的语句如下所示:

select 'product_x' as TableName, yyy 
from table_product_x 
union all 
select 'product_y' as TableName, yyy 
from table_product_y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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