tags:

views:

46

answers:

3

Say I have a table

MemberMoto ( MemberID int, Moto nvarchar(100) )

I need to build a proc that will return coma separated list of Moto values per user. I am looking for a way to accomplish this without using CURSOR/FETCH for performance reasons

Thank you!

A: 

One way to do this is by creating your own aggregate function. See http://technet.microsoft.com/en-us/library/ms131056.aspx

Gabe
Can you give an example?
Andrey
There is no need to go to a CLR function for this, way too much overhead to accomplish this simple task.
Mitchel Sellers
I always thought that was the best. Does anybody have benchmarks to show one way or the other?
Gabe
I just realized after Mitchel's comment that you can't create aggregate functions with T-SQL and you have to fall back to CLR. My question was about efficient way of concatinating strings, and using CLR is slow, hence a minus.
Andrey
Andrey: How do you know that CLR is slow? According to http://it.toolbox.com/blogs/paytonbyrd/clr-stored-procs-versus-tsql-stored-procs-round-2-10878 it can be quite fast. As I said, I'd love to see some benchmarks proving that I'm wrong.
Gabe
Gabe performance is one thing, another thing is security. a CLR function is NOT very deployable, and in many environments are still not allowed. Especially when there is a easy way to do it via TSQL
Mitchel Sellers
+7  A: 

I've used the following with great success, this gets a single user's information

DECLARE @results VARCHAR(MAX)
SELECT  @Results = COALESCE(@Results+ ', ' + Moto, Moto)
FROM    MemmberMoto
WHERE MemberId = 1
ORDER BY Moto

Now, you could then extrapolate this out to a function if you needed to call this once per user or something of that nature.

Mitchel Sellers
I love this example - simple and efficient!
Andrey
+2  A: 
create table MemberMoto (MemberID int, Moto nvarchar(100));

insert into MemberMoto values (1, 'joey');
insert into MemberMoto values (1, 'sally');
insert into MemberMoto values (2, 'yaochun');
insert into MemberMoto values (2, 'willy');

SELECT
   t1.MemberID,
   MotoList = substring((SELECT ( ', ' + Moto )
                           FROM MemberMoto t2
                           WHERE t1.MemberID = t2.MemberID
                           ORDER BY 
                              MemberID
                           FOR XML PATH( '' )
                          ), 3, 1000 )
FROM MemberMoto t1
GROUP BY MemberID

Results:

MemberID MotoList
1        joey, sally
2        yaochun, willy
dcp