sql-server - 如何在 SQL Server 中的 XML 投影中输出原始 xml,而不引入额外的 xml 根元素

标签 sql-server xml t-sql select-for-xml

下面的 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>

最佳答案

我认为你可以做到:

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您可以找到通配符作为列名称的文档。

关于sql-server - 如何在 SQL Server 中的 XML 投影中输出原始 xml,而不引入额外的 xml 根元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29925212/

相关文章:

sql-server - SQL Server 枢轴 : Displaying row values to column headers

sql-server - 动态分区值 SQL Server Azure Synapse

java - saveWebArchive() 不适用于 Android 4.0.3

sql - 使用CTE的相邻列表和递归查询,如何回填?

sql - 使用 SELECT MAX() 和 GROUP BY 时如何包含主键?

sql-server - SQL Server 中 View 的成本

sql-server - 使用 SQL 替换表中的引号字符

sql - 将值转换为单行

java - 为什么我的 9-patch 在Android中这么小?

Android解码xml文件中的html