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).
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.
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.
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.
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".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With