Function to get comma (delimited) separated values from Table in SQL Server

Last Reply 10 days ago By pandeyism

Posted 10 days ago

hello,

i am using this SP to get row values as comma seperated values, i want to covert this SP to functions so i can add the function in my existing SP query

COALESCE Example: Get comma (delimited) separated values from Table in SQL Server

Posted 10 days ago

Hi nauna,

Refer below sample query.

SQL

DROP FUNCTION GetCommaSeparatedString
GO
CREATE FUNCTION GetCommaSeparatedString(@City NVARCHAR(15))
RETURNS VARCHAR(MAX)
AS  
BEGIN
	DECLARE @Output VARCHAR(MAX)
	SELECT @Output = COALESCE(@Output + ',', '') + CAST(EmployeeId AS VARCHAR(5))
	FROM Employees
	WHERE City = @City
	RETURN @Output
END
GO
SELECT dbo.GetCommaSeparatedString('London') AS Ids