在SQL Server中粉碎XML数据

时间:2011-12-05 06:53:34

标签: sql-server-2008 xquery-sql

我需要将以下XML导入SQL Server 2008 R2:

<Role
  ID="ef63f979-c65d-421a-a214-7319c6279e13" >
  <Privileges>
    <Privilege ID="1" />
    <Privilege ID="2" />
    <Privilege ID="3" />
    <Privilege ID="4" />
    <Privilege ID="5" />
  </Privileges>
</Role>

我能够使用表变量并解析XML两次,但是无法在一个解析中将其转换为关系表。那可能吗?这是预期的结果集:

EF63F979-C65D-421A-A214-7319C6279E13    1   2011-12-05 06:51:11.9065096 EF63F979-C65D-421A-A214-7319C6279E13
EF63F979-C65D-421A-A214-7319C6279E13    2   2011-12-05 06:51:11.9065096 EF63F979-C65D-421A-A214-7319C6279E13
EF63F979-C65D-421A-A214-7319C6279E13    3   2011-12-05 06:51:11.9065096 EF63F979-C65D-421A-A214-7319C6279E13
EF63F979-C65D-421A-A214-7319C6279E13    4   2011-12-05 06:51:11.9065096 EF63F979-C65D-421A-A214-7319C6279E13
EF63F979-C65D-421A-A214-7319C6279E13    5   2011-12-05 06:51:11.9065096 EF63F979-C65D-421A-A214-7319C6279E13

谢谢,

拉​​吉

1 个答案:

答案 0 :(得分:0)

我可以提取这个:

DECLARE @input XML = '<Role
  ID="ef63f979-c65d-421a-a214-7319c6279e13" >
  <Privileges>
    <Privilege ID="1" />
    <Privilege ID="2" />
    <Privilege ID="3" />
    <Privilege ID="4" />
    <Privilege ID="5" />
  </Privileges>
</Role>'

SELECT
    @input.value('(/Role/@ID)[1]', 'uniqueidentifier') AS 'ID',
    T.C.value('(@ID)[1]', 'int') AS 'Privilege'
FROM
    @input.nodes('/Role/Privileges/Privilege') AS T(C)

提供输出:

ID                                     Privilege
EF63F979-C65D-421A-A214-7319C6279E13    1
EF63F979-C65D-421A-A214-7319C6279E13    2
EF63F979-C65D-421A-A214-7319C6279E13    3
EF63F979-C65D-421A-A214-7319C6279E13    4
EF63F979-C65D-421A-A214-7319C6279E13    5

但我不知道你的日期/时间来自.....