יום שני, 10 ביוני 2013

Comma delimited result in TSQL

I wanted to mimic the following behavior using T-SQL

  1: 
  2: String myStr = "";
  3: foreach ( String nextPerson in  PersonsList)
  4: {
  5:   if (myStr != "")
  6:   {
  7:   myStr+=",";
  8:   }   
  9:   myStr+= nextPerson; 
 10: }

I found the next solution for this problem:


  1: DECLARE @theNameList VARCHAR(MAX)
  2: SELECT TOP 4 @theNameList = COALESCE(@theNameList+',' , '') + [FirstName]
  3: FROM [AdventureWorks2008].[Person].[Person]
  4: SELECT @theNameList

Result:
Syed,Catherine,Kim,Kim
The COALESCE methods returns the first NOT NULL value from its argument list.So it add comma only if @theNameList is not empty

Other solution for the problem:


  1:  
  2: DECLARE @theNameList VARCHAR(MAX)
  3: SET @theNameList = ''
  4: SELECT  TOP 4 @theNameList = @theNameList + [FirstName] + ','
  5: FROM [AdventureWorks2008].[Person].[Person]
  6: SELECT SUBSTRING(@theNameList , 1, LEN(@theNameList)-1)

Resources for the solution :
http://blog.sqlauthority.com/2007/05/06/sql-server-creating-comma-separate-values-list-from-table-udf-sp/

אין תגובות:

הוסף רשומת תגובה