2

I have two tables

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

and

tbl_Keywords 
Key_ID   Keyword
1        Keyword1
2        Keyword2
3        Keyword3

and i need result as follow

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

Here Keywords in tbl_Products have datatype of varchar and Key_ID have a datatype of bigint.

I try with converting Column to CSV From reference Here

But not able to get such this result.

Thanks for help

0

1 Answer 1

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

Try it here: https://data.stackexchange.com/stackoverflow/q/116544/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Eriksson. Its a perfect solution for my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.