首页 > 代码库 > SQL xml转table

SQL xml转table

创建虚拟表@Tmp

DECLARE @Tmp TABLE(ID INT,Resulr XML)

--插入数据

INSERT INTO @Tmp (ID,Resulr) VALUES (1,<root><row><ID>1</ID><score>80</score></row><row><ID>2</ID><score>85</score></row></root>)
INSERT INTO @Tmp (ID,Resulr) VALUES (2,<root><row><ID>1</ID><score>90</score></row><row><ID>2</ID><score>75</score></row></root>)

--原结果集

SELECT * FROM @Tmp AS t

技术分享

<root>
  <row>
    <ID>1</ID>
    <score>80</score>
  </row>
  <row>
    <ID>2</ID>
    <score>85</score>
  </row>
</root>

--查询结果

SELECT t.ID,a.c1.value(ID[1],int) AS xID
    ,a.c1.value(score[1],int) AS score
FROM @Tmp AS t CROSS APPLY t.Resulr.nodes(root/row) a (c1)

技术分享

 

SQL xml转table