如何在 SQL 服务器中的 XML 投影中输出原始 xml 而无需引入额外的 xml 根元素

How to output raw xml within an XML projection in SQL Server without introducing an extra xml root element

给出下面的 T-SQL 片段,它试图构建 XML.

declare @table table
(
    col1 varchar(max),
    col2 varchar(max),
    col3 xml
)

declare @someXml xml = '
<innerRoot a="b">
    <child>1</child>
    <child>2</child>
    <child>3</child>
</innerRoot>
'

insert into @table values ('VALUE1', 'VALUE2', @someXml)

select 
    t.col1 as '@attribute1',
    t.col2 as '@attribute2',
    t.col3 as UnwantedElement
from @table as t
for xml path('Root'), type

结果 XML 是:

<Root attribute1="VALUE1" attribute2="VALUE2">
  <UnwantedElement>
    <innerRoot a="b">
      <child>1</child>
      <child>2</child>
      <child>3</child>
    </innerRoot>
  </UnwantedElement>
</Root>

如何在没有 UnwantedElement 的情况下获得相同的输出,使其看起来像下面的示例。

<Root attribute1="VALUE1" attribute2="VALUE2">
  <innerRoot a="b">
    <child>1</child>
    <child>2</child>
    <child>3</child>
  </innerRoot>
</Root>

经过一些实验后我想出的解决方案是使用 query 方法作为一种空操作来避免自动命名。

select 
    t.col1 as '@attribute1',
    t.col2 as '@attribute2',
    t.col3.query('/')
from @table as t
for xml path('Root')

让我这样做的概念是查询 innerRoot 和元素上的所有属性。但是,在我的实验中,我注意到在指定查询时不再将 col3 名称用作名称。


我对 SQL 服务器中的 XML 的一个抱怨是语法如何与许多开发人员(如我)习惯的传统 SQL 语法相结合现在解释未命名元素等重载概念并不总是那么容易。

我认为你可以做到:

declare @table table
(
    col1 varchar(max),
    col2 varchar(max),
    col3 xml
)

declare @someXml xml = '
<innerRoot a="b">
    <child>1</child>
    <child>2</child>
    <child>3</child>
</innerRoot>
'

insert into @table values ('VALUE1', 'VALUE2', @someXml)

select 
    t.col1 as '@attribute1',
    t.col2 as '@attribute2',
    t.col3 as [*]
from @table as t
for xml path('Root'), type

在这里msdn您可以找到通配符作为列名称的文档。