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 :
and like to get a comma delimited list of UserID then we will write code as :
Now execute above code and you will get a CSV string -
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 :
Now execute above code and you will get a CSV string -
----Have a nice day.........
Let's sat we have a table Products as :
UserID | UserName | |
6001581 | Amit | |
6001582 | Sumit | |
6001583 | Vineet | |
6001584 | Muthu | |
6001585 | Ranjan | |
6001586 | Sudheer |
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