用于xml path('')输出


9

当我运行以下

select t.type
  from (values ('Green'),('Blue'),('Red')) as t(type)
   for xml path('')

我收到此输出

<type>Green</type>
<type>Blue</type>
<type>Red</type>

如果我运行以下

select t.type + '/'
  from (values ('Green'),('Blue'),('Red')) as t(type)
   for xml path('')

我收到此输出

Green/Blue/Red/

为什么在select中添加串联会导致类型标签的删除和xml文件中一行的输出?运行SQL Server 2012。

Answers:


15

XML是骗子

添加串联字符串时,将丢失“路径元素”。

例如,如果您这样做:

SELECT t.type + '/' AS type
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML PATH('');

SELECT t.type + '/' 
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML PATH('type');

你得到这个:

<type>Green/</type>
<type>Blue/</type>
<type>Red/</type>

列名或别名用作路径元素。

其他一些示例可能会有所帮助

使用 RAW, ELEMENTS

SELECT t.type + '/'
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML RAW, ELEMENTS;

SELECT t.type + '/' AS type
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML RAW, ELEMENTS;

在第一个示例中,您将获得通用的“行”元素名称,而在第二个示例中,您将获得行/类型。

使用时RAW, TYPE

SELECT t.type + '/' AS type
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML RAW, TYPE;

SELECT t.type + '/'
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML RAW, TYPE;

第一个查询返回有效的XML,第二个查询抛出错误,因为path元素缺少标识符。

使用AUTO,表别名和列名将变为路径:

SELECT type + '/' AS type
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML AUTO;

SELECT type 
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML AUTO;

但是没有别名,您会收到类似的错误:

SELECT type + '/'
FROM   ( VALUES ( 'Green' ), ( 'Blue' ), ( 'Red' )) AS t ( type )
FOR XML AUTO;

我举个例子,FOR XML EXPLICIT但现在就开始喝酒对我来说是不负责任的。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.