[英]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.