I have a temp table variable that I need to update with something sort of like a comma delimited string.
declare @clients table (clientid int, hobbylist char(1000))
declare @hobbies table (clientid int, hobbynumber smallint)
insert into @clients values (3, '')
insert into @clients values (5, '')
insert into @clients values (12, '')
insert into @hobbies values (3, 4)
insert into @hobbies values (3, 5)
insert into @hobbies values (3, 7)
insert into @hobbies values (12, 3)
insert into @hobbies values (12, 7)
So @clients contains:
clientid hobbylist
---------------------------
3
5
12
And @hobbies contains:
clientid hobbylist
---------------------------
3 4
3 5
3 7
12 3
12 7
I need to update the @clients table so that it contains:
clientid hobbylist
---------------------------
3 4;;5;;7
5
12 3;;7
The closest thing that I found was this: How to concatenate multiple rows? But I can't understand how he is getting "one, two, three" looking at the what is marked as the correct answer.
I'm using SQL Server 2008 R2 64. I tried using a cursor but it was slow (and there will be tons of this type of thing in this sp).
What's the most efficient way to do this?
Edit:
From njk's suggestion, I tried this:
update c
set hobbylist=Stuff((
Select ';;' + cast(hobbynumber as char)
From @hobbies h
Where h.clientid = c.clientid
For XML Path('')
), 1, 1, '')
from @clients c
It didn't give me an error, but the result is so wacked, I can't find a good way to show it here.
e.g. Hobby list for client 3 looks like this:
;4 ;;5 ;;7
ALMOST works. Don't know where the spaces are coming from.
Edit 2.
Duh. I'm using cast. I need to trim the thing. This solution works for me on my server. I'm going to see if I can get ClearLogic's working, as well, so I can mark it as a correct answer.