【问题标题】:How to output raw xml within an XML projection in SQL Server without introducing an extra xml root element如何在 SQL Server 的 XML 投影中输出原始 xml,而不引入额外的 xml 根元素
【发布时间】:2015-04-28 16:44:02
【问题描述】:

鉴于下面的 T-SQL sn-p 尝试构造 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>

【问题讨论】:

    标签: sql-server xml tsql select-for-xml


    【解决方案1】:

    我认为你可以这样做:

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

    【讨论】:

      【解决方案2】:

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

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

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


      我对 SQL Server 中的 XML 的一个抱怨通常是语法如何与许多开发人员(例如我自己)习惯使用的传统 SQL 语法相结合,因此现在处理诸如未命名元素之类的重载概念并不总是那么容易应该被解释。

      【讨论】:

      • 列名没有出现在生成的xml中的原因是你查询的第3列根本没有名字!尝试用 CAST(t.col3 as xml) 替换 t.col3.query('/') 出于同样的原因,这也将起作用。此行为记录在此处msdn
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多