How do I avoid character encoding when using “FOR XML PATH”?

前端 未结 3 546
执念已碎
执念已碎 2020-12-08 02:06

I\'m looking to create a comma-separated list of values from a SQL Server 2005 table, just like in JanetOhara\'s question. I\'m using a query similar to the one presented i

3条回答
  •  广开言路
    2020-12-08 02:50

    See this post on Creating concatenated delimited string from a SQL result set and avoid character encoding when using “FOR XML PATH”

    An alternate approach would be to rely on concatenation of characters (of course sql is not great with string operations as it is developed to work with set theory)

    USE tempdb;
    GO 
    
    CREATE TABLE dbo.x ( y NVARCHAR(255) );
    INSERT dbo.x
    SELECT 'Sports & Recreation'
    UNION ALL
    SELECT 'x >= y'
    UNION ALL
    SELECT 'blat'
    UNION ALL
    SELECT '';
    
    DECLARE @delimitedText varchar(max)
    SET @delimitedText=''
    SELECT @delimitedText += CASE WHEN LEN(@delimitedText) > 0 THEN +','+ y ELSE y END
    FROM dbo.x 
    
    SELECT @delimitedText
    GO
    DROP TABLE dbo.x;
    GO
    

提交回复
热议问题