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

时间:2012-03-02 22:28:45

标签: sql sql-server 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

1 个答案:

答案 0 :(得分:1)

您可以使用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
相关问题