Thursday, February 9, 2012

A function that returns comma delimited results

Hi all,

I need to create a Function that returns a table that coverts the repeated results of its original (grouped on a certain column) and comma delimit a field.

I'll give an example, as I cant explain to well what I want.

I have this table:

ANSWER
ID TITLE QUESTIONID
0 y 1
1 n 1
2 y 2
3 n 3
4 m 3
5 y 3
6 n 4

and I want to create a function that will allow me to return the following, grouped by the question ID.

ANSWERS
TITLE QUESTIONID
y,n 1
y 2
n,m,y 3
n 4

Thanks,
Let me know if there is a more appropriate place to post this type of question.This should get you started.
create function dbo.udf(@.i int)
returns varchar(8000)
as
begin
declare @.s varchar(8000)
select @.s=isnull(@.s+',','')+Title
from Answers
where QuestionID=@.i
order by ID
return @.s
end
go
select dbo.udf(QuestionID) [Title],QuestionID
from (select distinct QuestionID
from Answers)Derived|||Thats fantastic!

I got as far as creating the function myself, but had no idea about the select you wrote.

Can I ask, what is Derived?
After integrating with my structure, I created a view which contains that SELECT, and then used that view as part of my query, and solving my issues. Thanks!!

Andre|||Derived is an alias for the derived table - virtual table formed by the inner select.
e.g.
select *
from (select OrderID from Northwind..Orders) as [derived table]

No comments:

Post a Comment