简体   繁体   English

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

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

I've searched some topics here but there have not been any answers which I need. 我在这里搜索了一些主题,但是没有任何需要的答案。 I want to make a query where I will join a table basing on the column name in the first table. 我想进行查询,在哪里我将基于第一个表中的列名加入一个表。

I'm using sql server so it would be appreciate if someone know solution for this technology. 我正在使用sql server,因此如果有人知道该技术的解决方案,将不胜感激。

Here is a sample what I wanna do: 这是我想做的一个示例:

Tables : 桌子

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

Output : 输出

product_x | simple_yyy_value1 | abcd
product_y | simple_yyy_value4 | efgh

Query ( sketch ) 查询草图

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

You can build this using union all and some dynamic SQL. 您可以使用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)

The statement executed will look something like this: 执行的语句如下所示:

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