2011-11-04 72 views
2

我有兩個表與轉換欄選擇到csv

tbl_Products 
ID Keywords 
1 1,2 
2 1,3 
3 2,3 

tbl_Keywords 
Key_ID Keyword 
1  Keyword1 
2  Keyword2 
3  Keyword3 

,我需要得到如下

Result 
ID Keywords keywordCSV 
1 1,2  Keyword1,Keyword2 
2 1,3  Keyword1,Keyword3 
3 2  Keyword2 

這裏的關鍵字tbl_Products有VARCHAR的數據類型和Key_ID具有bigint的數據類型。

我嘗試轉換列到CSV從參考Here

但沒能獲得這樣的這個結果。

感謝您的幫助

+0

SQL服務器/ MySQL的/甲骨文? – sll

+0

SQL Server.Thanks for reply – Gate

回答

3
declare @tbl_Products table(ID int, Keywords varchar(10)) 

insert into @tbl_Products values 
(1, '1,2'), 
(2, '1,3'), 
(3, '2,3') 

declare @tbl_Keywords table(Key_ID int, Keyword varchar(10)) 

insert into @tbl_Keywords values 
(1,  'Keyword1'), 
(2,  'Keyword2'), 
(3,  'Keyword3') 

select P.ID, 
     P.Keywords, 
     stuff((select ', '+K.keyword 
       from @tbl_Keywords as K 
       inner join P.XKeywords.nodes('/k') as KX(N)    
        on KX.N.value('.', 'int') = K.Key_ID 
       for xml path(''), type).value('.', 'varchar(max)'), 1, 2, '') as keywordCSV 
from (
     select ID, 
      Keywords, 
      cast('<k>'+replace(Keywords, ',', '</k><k>')+'</k>' as xml) as XKeywords 
     from @tbl_Products 
    ) as P 

這裏試試:http://data.stackexchange.com/stackoverflow/q/116544/

+0

謝謝埃裏克森。 它是我的問題的完美解決方案 – Gate