将xml数据读入SQL表

时间:2014-11-30 10:25:57

标签: sql xml sql-server-2008-r2

我想读取xml字符串并将数据推送到SQL表中。我在SQL变量中有这些数据

<Policy>
   <No>
       <old>1</old>
       <new>2</new>
   </No>
   <name>
       <old>xxx</old>
       <new>yyy</new>
   </name>
   <amount>
       <old>1000</old>
       <new>1500</new>
   </amount>
</Policy>
<Policy>
    <No>
        <old>3</old>
        <new>4</new>
    </No>
    <name>
        <old>aaa</old>
        <new>bbb</new>
    </name>
    <amount>
        <old>2000</old>
        <new>2500</new>
    </amount>
</Policy>
<Policy>
    <No>
        <old>5</old>
        <new>6</new>
    </No>
    <name>
        <old>qqq</old>
        <new>www</new>
    </name>
    <amount>
        <old>1000</old>
        <new>1500</new>
    </amount>
</Policy>

我想将数据解释为旧的&amp;新

喜欢

OLD

No   Name amount
-----------------    
1    xxx  1000
3    aaa  2000
5    qqq  1000

No   Name amount
----------------
2    yyy  1500
4    bbb  2500
6    www  1500

谢谢,

Kihtrak J

2 个答案:

答案 0 :(得分:2)

假设您在名为@XmlData的SQL Server变量中拥有此XML,您可以使用这些本机XQuery表达式来获取您要查找的内容:

-- select "old" data
SELECT
    OldNo = XC.value('(No/old)[1]', 'int'),
    OldName = XC.value('(name/old)[1]', 'varchar(25)'),
    OldAmount = XC.value('(amount/old)[1]', 'decimal(20,2)')
FROM 
    @XmlData.nodes('/Policy') AS XT(XC)

-- select "new" data
SELECT
    NewNo = XC.value('(No/new)[1]', 'int'),
    NewName = XC.value('(name/new)[1]', 'varchar(25)'),
    NewAmount = XC.value('(amount/new)[1]', 'decimal(20,2)')
FROM 
    @XmlData.nodes('/Policy') AS XT(XC)

答案 1 :(得分:1)

您的XML文档中只需要一个根(顶级)元素。

然后......尝试做这样的事情。

DECLARE @DocHandle int
DECLARE @XmlDocument nvarchar(max)
SET @XmlDocument = N'<ROOT><Policy>
   <No>
       <old>1</old>
       <new>2</new>
   </No>
   <name>
       <old>xxx</old>
       <new>yyy</new>
   </name>
   <amount>
       <old>1000</old>
       <new>1500</new>
   </amount>
</Policy>
<Policy>
    <No>
        <old>3</old>
        <new>4</new>
    </No>
    <name>
        <old>aaa</old>
        <new>bbb</new>
    </name>
    <amount>
        <old>2000</old>
        <new>2500</new>
    </amount>
</Policy>
<Policy>
    <No>
        <old>5</old>
        <new>6</new>
    </No>
    <name>
        <old>qqq</old>
        <new>www</new>
    </name>
    <amount>
        <old>1000</old>
        <new>1500</new>
    </amount>
</Policy></ROOT>'


-- Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @DocHandle OUTPUT, @XmlDocument

-- Execute a SELECT statement using OPENXML rowset provider.
SELECT *
FROM OPENXML (@DocHandle, '/ROOT/Policy/No', 2)
      WITH 
    (
        no_old varchar(200) 'old',
        no_new varchar(200) 'new',
        name_old varchar(200) '../name/old',
        name_new varchar(200) '../name/new',
        amount_old varchar(200) '../amount/old',
        amount_new varchar(200) '../amount/new'
    )

--- Clean up the internal representation.
EXEC sp_xml_removedocument @DocHandle

有关详细信息,请查看这两个MSDN页面:

OPENXML

OPENXML examples