DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
SITE SEARCH SQLUSA.com HEADLINES NEWS
SQL E/BOOKS   SQL 2014 PROGRAMMING   DOWNLOADS
SCRIPTS SQL 2005 SQL 2008 ARTICLES
SQL JOBS TWITTER FORMAT VIDEOS
How to generate comma separated list from a SELECT?

Execute the following T-SQL example scripts in Microsoft SQL Server Management Studio Query Editor to create and test a UDF for comma-limited list assembly.

-- Create user-defined function with input parameters
-- Scalar-valued string function – UDF
-- T-SQL String concatenation of comma-limited list
USE AdventureWorks;
GO
CREATE FUNCTION fnCSVList
               (@IDStart INT,
                @IDEnd   INT)
RETURNS VARCHAR(2048)
AS
  BEGIN
    DECLARE  @ResultString VARCHAR(2048)
    
    SELECT @ResultString = isnull(@ResultString,'') + [City] + ', '
    FROM   (SELECT DISTINCT [AddressID], [City]
            FROM   Person.[Address]) AS AliasZ
    WHERE  [AddressID] BETWEEN @IDStart AND @IDEnd
    
    IF len(@ResultString) > 0
      SET @ResultString = left(rtrim(@ResultString),
          len(rtrim(@ResultString)) - 1)
    
    RETURN @ResultString
  END
GO
-- Test user-defined function
SELECT dbo.fnCSVList (20,30)
GO
/* Results
 
Bothell, Bothell, Portland, Seattle, Duluth, Dallas, San Francisco,
Nevada, Phoenix, Memphis, Orlando

*/

------------
 

Exam Prep 70-461
Exam 70-461
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE