2012-03-02 76 views
1

我在這裏搜索了一些主題,但沒有任何我需要的答案。 我想做一個查詢,我將根據第一個表中的列名加入一個表。從列表中選擇記錄作爲列名。動態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 
+0

這將是有益的,如果你可以添加一些樣本數據,你的表和預期產出的問題。 – 2012-03-02 22:39:09

+0

已經更新 – nosbor 2012-03-02 22:49:10

回答

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 
+0

不錯的解決方案,但是我怎樣才能在這個選擇中加入?看看我的問題中的輸出示例。 – nosbor 2012-03-03 08:27:14

+0

@nosbor我不明白。這會給你你想要的結果。你需要加入什麼?請更新您的問題。 – 2012-03-03 08:37:14

+0

您的查詢在第一列中提供了表名,而不是從main_table中選項卡列。我更新了我的問題以突出顯示我想要做的事情。請參閱main_table,示例查詢和輸出。 – nosbor 2012-03-03 09:29:21