Get SQL result rows into one variables

Below is a quick tip to convert rows into variable(comma separated)

declare @tmpEmployee table (EmployeeName nvarchar(200))
declare @commaSeperatedNames nvarchar(max)
 
insert into @tmpEmployee Values('A')
insert into @tmpEmployee Values('B')
insert into @tmpEmployee Values('C')
insert into @tmpEmployee Values('F')
insert into @tmpEmployee Values('AH')
insert into @tmpEmployee Values('AJJ')
insert into @tmpEmployee Values('AH')
 
 
select EmployeeName  from @tmpEmployee
 
 
select EmployeeName +',' from @tmpEmployee FOR XML PATH('')
 
select @commaSeperatedNames =
STUFF(
		(select EmployeeName +',' from @tmpEmployee FOR XML PATH(''))
     ,1,1,''
   )
    select @commaSeperatedNames 
 
 
Here is the results
image

WordPress Tags: EmployeeName,Values,PATH,STUFF,Here,tmpEmployee,nvarchar,commaSeperatedNames

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s