we want to concatenate one column row values into single row we need to write query like this
DECLARE @name NVARCHAR(MAX)
SELECT @name = COALESCE(@name + ',', '') + UserName FROM UserDetails
SELECT UserNames = @name
If you observe above query I used function COALESCE it returns the first non-null expression among its arguments.
Another way
If we want to concatenate rows of column we can write query like as shown below
DECLARE @name NVARCHAR(MAX)
SET @name=''
SELECT @name = @name +','+UserName FROM UserDetails
SET @name = Substring(@name, 2, (len(@name)))
SELECT @name as UserNames
check this