--Create sample table
Create Table #Temp
(
PkValue int
)
--Insert sample data
Insert Into #Temp Values (1)
Insert Into #Temp Values (2)
Insert Into #Temp Values (3)
Insert Into #Temp Values (1)
Insert Into #Temp Values (2)
Insert Into #Temp Values (3)
--Declare and initialise variable
Declare @Ids nvarchar(max)
Set @Ids = ''
--Get distinct comma seperated values into variable
Select @Ids = (@Ids + Coalesce(Case when CHARINDEX(Convert(nvarchar(max),PkValue) + ',',@Ids) > 0 Then '' Else convert(nvarchar(max),PkValue)+ ',' End,'' ))
From #Temp
--Verify output with sample data used
Select @Ids
Select * From #Temp
--Drop sample table
Drop Table #TempThis sql snippet demonstrates how to get single comma separated value from set of column values in MS-SQL
