gpt4 book ai didi

sql-server - SQL Server 用于具有双元素的 xml 路径

转载 作者:行者123 更新时间:2023-12-02 23:29:46 25 4
gpt4 key购买 nike

我正在尝试使用 FOR XML PATH 在 SQL Server 2012 中创建 xml 输出。
可以做什么来获得所需的输出?

我想输出为:

<types>
<type>
<type>FirstType</type>
<attribute>FirstAttribute</attribute>
</type>
</types>
<types>
<type>
<type>SecondType</type>
<attribute>SecondAttribute</attribute>
</type>
</types>
<types>
<type>
<type>ThirdType</type>
<attribute>ThirdAttribute</attribute>
</type>
</types>

我的代码:

DECLARE @table TABLE (
type VARCHAR(50)
, attribute VARCHAR(50)
)

SELECT T1.type
, T1.attribute
FROM @table AS T1
FOR XML path('type'), root('types')

给我错误的输出:

<types>
<type>
<type>FirstType</type>
<attribute>FirstAttribute</attribute>
</type>
<type>
<type>SecondType</type>
<attribute>SecondAttribute</attribute>
</type>
<type>
<type>ThirdType</type>
<attribute>ThirdAttribute</attribute>
</type>
</types>

最佳答案

这将返回您想要的内容:

DECLARE @table TABLE (
[type] VARCHAR(50)
, attribute VARCHAR(50)
)
INSERT INTO @table VALUES('FirstType','FirstAttribute')
,('SecondType','SecondAttribute')

SELECT T1.type AS [type/type]
, T1.attribute AS [type/attribute]
FROM @table AS T1
FOR XML path('types');

但要注意:由于缺少根节点,它是无效的。 SQL-Server 的 XML 引擎可以处理这个问题,但其他引擎可能会失败......

我认为,SQL Server 并不那么严格,因为 XML 通常是由多个片段构建的。这样的结果可能是这些片段之一,没有任何问题......

关于sql-server - SQL Server 用于具有双元素的 xml 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48504855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com