如何使用TSQL FOR XML生成每行一个元素。

huangapple go评论65阅读模式
英文:

How to use TSQL FOR XML to generate one element per row

问题

我想生成以下XML:

<students>
    <name>Alice</name>
    <name>Bob</name>
    <name>Charles</name>
</students>

不要生成以下XML:

<students>
    <row><name>Alice</name></row>
    <row><name>Bob</name></row>
    <row><name>Charles</name></row>
</students>

是否可以使用TSL的FOR XML子句来实现这个目标?

请注意,对生成的XML进行文本替换不算在内。我已经知道string_agg()了。

英文:

Given the following query:

select name from student

I want to generate the following XML:

<students>
    <name>Alice</name>
    <name>Bob</name>
    <name>Charles</name>
</students>

I do not want to generate the following XML. The code consuming the generated XML won't accept anything but the format shown above.

<students>
    <row><name>Alice</name></row>
    <row><name>Bob</name></row>
    <row><name>Charles</name></row>
</students>

Can this be done with TSL's FOR XML clause?

Text replacement on the resulting XML doesn't count. I can do that already. I already know string_agg(), too.

答案1

得分: 2

有两种方法可以实现这个,取决于你希望其他列如何显示。

要么不使用 PATH,这将保留其他列使用它们自己的节点名称,但没有父节点。

SELECT
  s.name
FROM student s
FOR XML PATH(''), ROOT('students'), TYPE;

要么使用一个无名称的列,在其中其他无名称的列将被合并成一个文本值,位于 <name> 内。

SELECT
  s.name + ''
FROM student s
FOR XML PATH('name'), ROOT('students'), TYPE;
英文:

There are two methods to do this, depending on how you would want other columns to show up.

Either use no PATH, which would keep other columns using their own node names, but no parent node.

SELECT
  s.name
FROM student s
FOR XML PATH(&#39;&#39;), ROOT(&#39;students&#39;), TYPE;

Or an unnamed column, where other unnamed colums would be squashed together into a single text value inside &lt;name&gt;

SELECT
  s.name + &#39;&#39;
FROM student s
FOR XML PATH(&#39;name&#39;), ROOT(&#39;students&#39;), TYPE;

huangapple
  • 本文由 发表于 2023年6月22日 04:02:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定