Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 tricky query (atleast for me)

Author  Topic 

joshb
Yak Posting Veteran

52 Posts

Posted - 2002-06-20 : 16:57:49
I have 2 tables with a one to many relationship between them. How can I write a select query which would produce the following result:

OneTableField ManyTableField
value_1 value_1, value_2, value_3
value_2 value_4, value_5
value_3 value_6, value_7

Basically for each row I want a field with a value from the OneTable then another field listing the related values from the ManyTable in a comma seperated list.

I have some ideas on how to do this with cursors but would rather not use them if I can avoid it.

Any ideas?

MichaelP
Jedi Yak

2489 Posts

Posted - 2002-06-20 : 17:49:32
This is not directed at anyone in particular, but newbies are esp. guilty of this.

<rant>
Please search through some of the really great articles on the site before posting!
</rant>

Josh,
goto http://www.sqlteam.com/Search.asp
type in csv in the search box, and hit search. Your answer awaits.

Michael

Go to Top of Page

VyasKN
SQL Server MVP &amp; SQLTeam MVY

313 Posts

Posted - 2002-06-20 : 17:58:11
Try this: http://www.sqlteam.com/redir.asp?ItemID=9629

--
HTH,
Vyas
http://vyaskn.tripod.com
Go to Top of Page

joshb
Yak Posting Veteran

52 Posts

Posted - 2002-06-21 : 10:34:58
If anyone is interested I solved this one using the COALESCE method explained by Garth in his article "Using COALESCE to Build Comma-Delimited String". His article explains how to produce a list for a single OneTable value. I wrapped this in a UDF then used the UDF in a correlated subquery passing in the OneTable ID from the outer query and using it as a parameter for the UDF (the inner query). Once again UDFs save the day!

Example:
SELECT OneTable.ID, (SELECT dbo.fnCSV(OneTable.ID)) AS ManyList
FROM OneTable

It performs pretty well too!

Thanks to MichaelP and VyasKN for pointing me in the right direction


Go to Top of Page
   

- Advertisement -