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

痴心易碎 提交于 2019-11-28 04:51:18
Aaron Bertrand

You just need to use the right options with FOR XML. Here's one approach that avoids encoding:

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 '';

-- BAD:
SELECT STUFF((SELECT N',' + y
  FROM dbo.x 
  FOR XML PATH(N''))
,1, 1, N'');

-- GOOD:
SELECT STUFF((SELECT N',' + y
  FROM dbo.x 
  FOR XML PATH, TYPE).value(N'.[1]', N'nvarchar(max)')
,1, 1, N'');

GO
DROP TABLE dbo.x;
Lin

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 '<hooah>';

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!