Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concatenating Row Values into 1 Record/String (revisited)

T-SQL Hints and Tips

Concatenating Row Values into 1 Record/String (revisited)

by  NoCoolHandle  Posted    (Edited  )
I discovered this by mistake, but is simplifies a difficult job...
Code:
  [green]-- Declare a variable to concatinate all the rows into..--[/green]
   Declare @x as varchar(800)
  [green]-- Set a default value that is not null -- [/green] 
   Set @x=''

  [green] -- in the select add the variable to itself and the value in the column and a comma --[/green]
   select @x= @x + cast(OrderId as varchar(200))  
   + ','  from Northwind.dbo.Orders

  [green]-- Retrieve vaules and strip of the last comma--[/green]
  select left(@x,len(@x)-1)
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top