sql server读取xml doc

时间:2013-11-25 01:16:30

标签: sql-server xml

我的请求xml采用这种格式

  <Tr>
    <Row id="50000" type =A/> 
    <Row id="50002" type =B/> 
    <Row id="50003" type =C/>
    <Row id="50004" type =C/>
   </Tr>

SQL Server中是否有办法在存储过程中解析此xml并创建临时表以此格式填写记录

Type A - 50000
Type B - 50002
Type C - 50003,500004

或者这种格式

Type     id
A       50000
B       50002
C       50003
C       50004
  • 列表项

1 个答案:

答案 0 :(得分:1)

一旦你的XML成为有效的 XML,那么是的,你可以轻松地将它解析为T-SQL中的行和列:

此处,@input变量定义为XML并设置固定值 - 这可能是存储过程中的输入参数

DECLARE @input XML = '<Tr>
    <Row id="50000" type="A" /> 
    <Row id="50002" type="B" /> 
    <Row id="50003" type="C" />
    <Row id="50004" type="C" />
   </Tr>'

SELECT
    Type = XCol.value('@type', 'varchar(10)'),
    ID = XCol.value('@id', 'int')
FROM 
    @input.nodes('Tr/Row') AS XTbl(XCol)

为您提供所需的输出(第二种样式 - XML中每<Row>个条目一行)