Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server sub query with a comma separated resultset

Tags:

I need to return records on a table and my result set needs to contain a comma separated list.

I have attached an image of the 3 tables. I need to do a select that returns the record in the first table and include the last of AwardFocusName that exist in the 3rd table in the screenshot.

So my result set would return one record and include the list of AwardFocusNames in it (comma separated).

enter image description here

like image 645
obautista Avatar asked Nov 28 '11 21:11

obautista


People also ask

How can we get result in Comma Separated Values from SQL query?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.

Can subquery return a tabular result?

A column subquery returns a single column of one or more values. A row subquery returns a single row of one or more values. A table subquery returns a table of one or more rows of one or more columns.

How do you enclose a sub query?

Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.


2 Answers

Here's a trick I've used in the past to do similar things. Use SUBSTRING function.

      SELECT n.nominationID         , SUBSTRING((                             SELECT ',' + naf.awardFocusName                             FROM NominationAwardFocus naf                             JOIN AwardFocus af                                 ON naf.awardFocusID = af.awardFocusID                             WHERE n.nominationID = naf.nominationID                             FOR XML PATH('')                          ), 2, 1000000)     FROM Nomination n  

Note that the 2 is used to chop off the leading comma that the subselect adds to the first item, and 1000000 is chosen as a large number to mean "all of the rest of the string".

like image 162
Alex Avatar answered Oct 02 '22 15:10

Alex


Create a Scalar-valued Function like this

CREATE FUNCTION [dbo].[CreateCSV](     @Id AS INT ) RETURNS VARCHAR(MAX) AS BEGIN     Declare @lst varchar(max)      select @lst = isnull(@lst+',','')+AF.AwardFocusName     from AwardFocus as AF     inner join AwardFoccusNomination as AFN         on AF.AwardFocusID = AFN.AwardFocusID     where AFN.NominationID=@Id       return @lst  END 
like image 28
wcm Avatar answered Oct 02 '22 15:10

wcm