使用“FOR XML PATH"时如何避免字符编码? [英] How do I avoid character encoding when using "FOR XML PATH"?

查看:29
本文介绍了使用“FOR XML PATH"时如何避免字符编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从 SQL Server 2005 表中创建一个逗号分隔的值列表,就像在 JanetOhara 的问题中一样.我使用的查询类似于 techdo's answer 中提出的问题.

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 in techdo's answer to the question.

一切正常,除了值列表被 XML 编码.应该是什么:

Everything is working, except the list of values is getting XML encoded. What should be:

Sports & Recreation,x >= y

而是返回为:

Sports & Recreation,x <= y

在 SQL Server 中使用FOR XML"时,有没有办法禁用 XML 字符编码?

Is there a way to disable the XML character encoding when using "FOR XML" in SQL Server?

推荐答案

您只需要在 FOR XML 中使用正确的选项.这是一种避免编码的方法:

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

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

如果您使用的是较新版本的 SQL Server (2017+),您可以使用 STRING_AGG() 并且完全不用担心 XML:

If you are on a newer version of SQL Server (2017+), you can use STRING_AGG() and not worry about XML at all:

SELECT STRING_AGG(y, N',') FROM dbo.x;

db<>fiddle 演示了所有三个.

这篇关于使用“FOR XML PATH"时如何避免字符编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆