How to get column values into variable as a comma seperated value ?
-
Friday, February 08, 2013 5:58 AM
Hi,
I have a column where i have values in row by row basis, i want to gt them into one variable as a comma seperated.
for example i have-
EMPID
1
2
3
4
i want @ID=1,2,3,4
Please suggest approach!!!!
All Replies
-
Friday, February 08, 2013 6:10 AM
Try the below:
Create Table Emp(EmpId int) Insert into Emp Select 1 Insert into Emp Select 1 Insert into Emp Select 2 Insert into Emp Select 3 Declare @empids varchar(100) = '' Set @empids = (select distinct STUFF( (SELECT DISTINCT ', ' + cast(EmpId as varchar(100)) FROM emp b FOR XML PATH('') ), 1, 2, '') company_referred from emp a); Select @empids
Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.
- Marked As Answer by Maggy111 Friday, February 08, 2013 6:25 AM
-
Friday, February 08, 2013 6:16 AM
Try
SELECT @id=stuff( (SELECT ', ' + empid
FROM tab1 b
ORDER BY empid
FOR XML PATH('')),1 ,2 ,'');go
Many Thanks & Best Regards, Hua Min
- Marked As Answer by Maggy111 Friday, February 08, 2013 6:26 AM
-
Friday, February 08, 2013 6:16 AM
If you google the question to make rows to comma separated, i will get numerous solutions including the same question and answer from this forum as well. One thread is here:
How to combine values of a column in one row separated by comma
Here is a comprehensivearticle on this:
Making a List (and Checking It Twice) - Brad Schulz
Krishnakumar S
- Marked As Answer by Maggy111 Friday, February 08, 2013 6:26 AM
-
Friday, February 08, 2013 6:21 AM
try this :
DECLARE @t TABLE (ID int) DECLARE @Ids VARCHAR(100) Insert into @t values(1),(2),(3) select @Ids = (stuff((select ',' + cast(Id as varchar) from @t for xml path('')),1,1,'')) select @Ids
Please vote if you find this posting was helpful or Mark it as answered.
- Marked As Answer by Maggy111 Friday, February 08, 2013 6:26 AM

