question

Ronakshah112 avatar image
Ronakshah112 asked

CSV values in table

Table 1 output NAME abc bcd abnc,bcnc,dcnc asdf,fdas,dcnd abcd Table 2 Output ID NAME 1 abc 2 bcd 3 abnc 4 bcnc 5 dcnc 6 asdf 7 fdas 8 dcnd I need output in result set like below NAME IDs abc 1 bcd 2 abnc,bcnc,dcnc 3, 4, 5 asdf,fdas,dcnd 6, 7, 8
t-sql
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Scot Hauder avatar image
Scot Hauder answered
SELECT * FROM ( SELECT t3.NAME,(SELECT STUFF((SELECT ',' + CAST(ID AS varchar(20)) FROM Table1 t1 JOIN Table2 t2 ON (CHARINDEX(',' + REPLACE(t2.NAME, ' ','') + ',', ',' + REPLACE(t1.NAME, ' ','') + ',' ) > 0) WHERE t1.NAME = t3.NAME ORDER BY ID FOR XML PATH('')),1,1,''))[IDs] FROM Table1 t3)d WHERE IDs IS NOT NULL
3 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Tim avatar image Tim commented ·
congrats on 4k.
0 Likes 0 ·
Ronakshah112 avatar image Ronakshah112 commented ·
Thanks Scot. It works for me.
0 Likes 0 ·
Oleg avatar image Oleg commented ·
@Ronakshah112 If it does, could you please mark Scot's answer as accepted? There is a box next to the voting buttons to the left of the question. It is visible only to the person who asked the question. The technique used by Scot to avoid an extra step of splitting the rows in table1 before joining the data with table2 is not trivial and could prove to be very useful to other site's users.
0 Likes 0 ·
KenJ avatar image
KenJ answered
8 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Tim avatar image Tim commented ·
We should probably think about a commonly asked question section that is easier to search. We could make some cool screen shots and step by step how to's that could help lots of people.
3 Likes 3 ·
Oleg avatar image Oleg commented ·
@KenJ It looks like OP might have either a single or comma-delimited list of names in table1 and ID and NAME in table2. This was not easy to see before I edited the question. Now it looks like the join is on the "split" values of table1 and NAME of table2 and "join" of the matches
1 Like 1 ·
Pavel Pawlowski avatar image Pavel Pawlowski commented ·
Yeah, asked many times here.
0 Likes 0 ·
KenJ avatar image KenJ commented ·
That's a great idea. Multi-word searching is *painful*
0 Likes 0 ·
Ronakshah112 avatar image Ronakshah112 commented ·
By using above query I am not able to get my exact output. Here is the query: SELECT cast ( T.ID as varchar), STUFF((SELECT ',' + NAME FROM #tab1 T2 WHERE T2.NAME = T.NAME FOR XML PATH('')) ,1, 1, '') AS Y FROM #tab2 T Please Help to resolve this issue.
0 Likes 0 ·
Show more comments

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.