57

Right now, I have a SQL Query like this one:

SELECT X, Y FROM POINTS

It returns results like so:

X    Y
----------
12   3
15   2
18   12
20   29

I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag):

XYLIST
----------
12,3,15,2,18,12,20,29

Is there a way to do this using just SQL?

Joshua Carmody
  • 13,410
  • 16
  • 64
  • 83

5 Answers5

101

Thanks for the quick and helpful answers guys!

I just found another fast way to do this too:

SELECT  STUFF(( SELECT ',' + X + ',' + Y
                FROM Points
              FOR
                XML PATH('')
              ), 1, 1, '') AS XYList

Credit goes to this guy:

Link

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Joshua Carmody
  • 13,410
  • 16
  • 64
  • 83
  • I really like this solution the most. Easy to use and only one line to add in any SQL. – Tai Kahar Oct 23 '12 at 09:30
  • 2
    Note: This method causes special characters to be replaced by their XML equivalent. IOW, Barnes & Noble becomes Barnes & Noble – SvdSinner Apr 30 '18 at 20:31
31
DECLARE @XYList varchar(MAX)
SET @XYList = ''

SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','
FROM POINTS

-- Remove last comma
SELECT LEFT(@XYList, LEN(@XYList) - 1)
Ben Hoffstein
  • 102,129
  • 8
  • 104
  • 120
  • Is it me or doesn't this work on a linked server? When i try something like `SELECT @List = @List + CONVERT(varchar, ID) + ',' FROM LinkedServer.MyDatabase.dbo.MyTable` it always returns only one ID. A `Select *` returns many ID's. – Martin Nov 05 '14 at 13:42
16

Starting in SQL 2017, you can use STRING_AGG

SELECT STRING_AGG (X + ',' + Y, ',') AS XYLIST
FROM POINTS

https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

Carter Medlin
  • 11,857
  • 5
  • 62
  • 68
15

Using the COALESCE trick, you don't have to worry about the trailing comma:

DECLARE @XYList AS varchar(MAX) -- Leave as NULL

SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y)
FROM POINTS
Cade Roux
  • 88,164
  • 40
  • 182
  • 265
1
DECLARE @s VarChar(8000)
SET @s = ''

SELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar) 
FROM POINTS

SELECT @s 

Just get rid of the leading comma

Peter
  • 3,563
  • 5
  • 30
  • 43