0

Is there another way to do this without the XML function? I've tried following Concatenate many rows into a single text string? I'm having issues trying to run this on SQL Server 2008 R2.

Conversion failed when converting the varchar value ',' to data type int.

Select distinct ST2.id 
    substring(
        (
            Select ','+ST1.id AS [text()]
            From dbo.idstable ST1
            Where ST1.id = ST2.id
            ORDER BY ST1.id
            For XML PATH ('')
        ), 2, 1000) [idstable]
From dbo.idstable ST2
Sql_Pete_Belfast
  • 570
  • 4
  • 23

2 Answers2

1

The reason for the syntax error is the extraneous column name after DISTINCT. Below is a similar method that uses STUFF and TYPE to avoid issues with special characters in the string.

SELECT DISTINCT
    STUFF(
        (
            SELECT ','+CAST(ST1.id AS varchar(10)) AS [text()]
            FROM dbo.idstable ST1
            WHERE ST1.id = ST2.id
            ORDER BY ST1.id
            FOR XML PATH (''), TYPE
        ).value('.', 'nvarchar(MAX)'), 1, 1, '') [Students]
FROM dbo.idstable ST2;

The other supported method for aggregate string concatenation on older SQL versions is a cursor.

Dan Guzman
  • 43,250
  • 3
  • 46
  • 71
1

Dan's answer is correct, as far as it goes. From a performance perspective, it is better to do the distinct in a subquery (and probably to include the id in the outer query:

SELECT id
       STUFF( (SELECT ',' + CAST(ST1.id AS varchar(10)) AS [text()]
               FROM dbo.idstable ST1
               WHERE ST1.id = ST2.id
               ORDER BY ST1.id
               FOR XML PATH (''), TYPE
              ).value('.', 'nvarchar(MAX)'
                     ), 1, 1, '') as [Students]
FROM (SELECT DISTINCT id dbo.idstable) ST2;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786