sql - 在 SQL Server 中使用 XQuery 将 XML 转换为表数据

标签 sql xquery-sql

是否可以在 SQL Server 中使用 XQuery 实现下表的输出

编辑:我的要求发生了变化,考虑我有一个存储以下 xml 和 UserID 的表

DECLARE  @XML xml
set @XML = '<Security>
             <FiscalYear Name="2012">
            <Country Id="204">
              <State Id="1">
                <City Id="10"></City>
              </State>
              <State Id="2">
                <City Id="20"></City>
                <City Id="30"></City>
              </State>
              <State Id ="3"></State>
              </Country >
            </FiscalYear>
        </Security>'

CREATE TABLE #tmp_user
(UserID INT,SecurityXML XML)

INSERT INTO #tmp_user
        ( UserID, SecurityXML )
VALUES  ( 1, 
          @XML
          )

现在我怎样才能得到像这样的o/p

输出:

 UserID StateID       CityID
     1      1           10
     1      2           20
     1      2           30
     1      3            0

可以实现吗?

最佳答案

我对您的 XML 进行了一些修改,因为它无效。更改结束标记</Subsidiary></Country> .

declare @XML xml
set @XML = 
'<Security>
   <FiscalYear Name="2012">
     <Country Id="204">
      <State Id="1">
        <City Id="10"></City>
      </State>
      <State Id="2">
        <City Id="20"></City>
        <City Id="30"></City>
      </State>
      <State Id ="3"></State>
    </Country>
   </FiscalYear>
 </Security>'

select S.N.value('@Id', 'int') as StateID,
       coalesce(C.N.value('@Id', 'int'), 0) as CityID
from @XML.nodes('/Security/FiscalYear/Country/State') as S(N)
  outer apply S.N.nodes('City') as C(N)

使用表格而不是 XML 变量的版本

select T.UserID,
       S.N.value('@Id', 'int') as StateID,
       coalesce(C.N.value('@Id', 'int'), 0) as CityID
from #tmp_user as T
  cross apply T.SecurityXML.nodes('/Security/FiscalYear/Country/State') as S(N)
  outer apply S.N.nodes('City') as C(N)

关于sql - 在 SQL Server 中使用 XQuery 将 XML 转换为表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7400366/

相关文章:

sql-server - 使用 XQuery 连接 XML 节点

sql-server - XQuery 在单个 SQL 更新命令中添加或替换属性

sql-server - 需要帮助 Local.name(.) xquery 函数

mysql - 在名称字段上进行 GROUP BY,选择 ID 最小的行

mysql - 如何使用查询替换文本

PHP - 使用一组 ID 从数据库中删除许多项目

sql-server - 根据同级其他节点的值更新节点值 XML T-SQL

sql - 相当于XQuery中的AS?

mysql - SQL 查询合并两个表,同时还显示一个表中的所有记录

java - Hibernate,如果不使用beginTransaction会发生什么?