如何将XML标记名称和值转换为列值

时间:2015-08-19 07:24:07

标签: sql sql-server xml

我将以下XML存储在SQL Server数据库中的XML数据类型列(称为auditinfo)中。我希望root之后的所有标记都列在名为LocalName的列标题下,以及要在名为LocalValue的标题下列出的标记内的相应值。

/** example data in row 1  of the auditinfo column **/
<root>
<Key>50</Key>
<OrderNumber>123</OrderNumber>
<OrderStatus>Ready</OrderStatus>
<CreatedBy>Tom Smith</CreatedBy>
<ReadyDateTime>2015-06-27T10:24:15.743Z</ReadyDateTime>
</root> 


/** example data in row 2  of the auditinfo column **/
<root>
<Key>100</Key>
<Signature>Jill Smith</Signature>
<DeliveryNumber>500</DeliveryNumber>
</root>

2 个答案:

答案 0 :(得分:2)

我希望您正在寻找类似的东西 -

    SELECT T.C.value('fn:local-name(.)', 'nvarchar(50)') AS LocalName,
       T.C.value('.','VARCHAR(MAX)') AS LocalValue  
FROM YourXmlTable 
CROSS APPLY [auditinfo].nodes('/root/*') AS T(C)

答案 1 :(得分:0)

这可以保存为

keys  ordernumber orderstatus createdby    readydatetime
50     123         ready      tom simth    2015-06-27T10:24:15.743Z

如果你想这样我有解决方案

@XMLVariable nvarchar(max)-- parameter from front end


Declare @XMLorderList as xml
set @XMLOrderList=@XMLVariable 


IF Object_id('tempdb..#tempLocaltable') Is Not Null     
            Drop table #tempLocaltable

    CREATE TABLE #tempLocaltable
     (
        key nvarchar(100),
        OrderNumber nvarchar(200),
        OrderStatus nvarchar(200),
        Createdby nvarchar(200),
        ReadyDateTime nvarchar(200),        
        )   

INSERT INTO #tempLocaltable
    SELECT * FROM 
    ( SELECT 
        x.rec.value('key[1]', 'nvarchar(100)') as key,
        x.rec.value('Ordernumber[1]', 'nvarchar(200)') as ordernumber,
        x.rec.value('Orderstatus[1]','nvarchar(200)') as orderstatus,
        x.rec.value('createdby[1]','nvarchar(200)') as createdby,
        x.rec.value('ReadyDateTime[1]','nvarchar(200)') as ReadyDateTime


    FROM @XMLOrderList.nodes('/root') x(rec) ) t




 insert into urtable (key,ordernumber,orderstatus,createdby,readydate)
        (select key,ordernumber, orderstatus,createdby,readydate from          
   #tempLocaltable)