Tuesday 10 July 2012

Comma Separated Value(CSV) String

        It is sometimes found that to make a Comma Separated Value(CSV) strings, Developers do a bit hard work and create functions with applying some longer logics and get the output for the same. But better if you can use a simple and short logic as below :

Let's sat we have a table Products as :
  
UserIDUserName
6001581Amit
6001582Sumit
6001583Vineet
6001584Muthu
6001585Ranjan
6001586Sudheer


  and  like to get a comma delimited list of UserID then we will write code as :   

   DECLARE @listStr VARCHAR(MAX)
   SELECT @listStr = COALESCE(@listStr+',' ,'') + UserID
   FROM  Products
  
   SELECT @listStr


Now execute above code and you will get a CSV string -

6001581,6001582,6001583,6001584,6001585,6001586


 In the above output you will have a string of UserID's without enclosed in single quotes..
So in order to get the same output with single quotes do as below :

   DECLARE @listStr VARCHAR(MAX)
   SELECT @listStr = COALESCE(@listStr+',' ,'') + '''' + UserID + ''''
   FROM  Products

   SELECT @listStr


Now execute above code and you will get a CSV string -

'6001581','6001582','6001583','6001584','6001585','6001586'





----Have a nice day.........

No comments:

Post a Comment