将XML节点插入表中的SQL列

时间:2016-03-01 14:01:56

标签: sql sql-server xml

我有一个XML文件,我将其传递给存储过程。

我也有一张桌子。该表有VehicleReg |列XML | ProcessedDate

我的XML就像这样:

<vehicles> 
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
</vehicles>

我需要做的是读取xml并将vehiclereg和整车xml字符串插入每一行(dateprocessed是一个getdate()所以没问题)。

我正在做类似下面的事情,但没有运气:

DECLARE @XmlData XML
Set @XmlData = EXAMPLE XML
SELECT T.Vehicle.value('(vehiclereg)[1]', 'NVARCHAR(10)') AS vehiclereg,
       T.Vehicle.value('.', 'NVARCHAR(MAX)'),
       GETDATE()
FROM @XmlData.nodes('Vehicles/Vehicle') AS T(Vehicle)

我想知道是否有人可以指出我正确的方向?

此致

3 个答案:

答案 0 :(得分:4)

只需记住XML区分大小写。你有:

FROM @XmlData.nodes('Vehicles/Vehicle') AS T(Vehicle)

但你应该有:

FROM @XmlData.nodes('/vehicles/vehicle') AS T(Vehicle)

同样,TT指出没有名为Registration

的列

这应该这样做:

DECLARE @XmlData XML
Set @XmlData = '<vehicles> 
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
</vehicles>'
SELECT  Vehicle.value('(vehiclereg)[1]', 'NVARCHAR(10)') AS vehiclereg,
        Vehicle.value('.', 'NVARCHAR(MAX)'),
       GETDATE()
FROM @XmlData.nodes('/vehicles/vehicle') AS T(Vehicle)

结果:

enter image description here

这将返回XML:

DECLARE @XmlData XML
Set @XmlData = '<vehicles> 
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
</vehicles>'
SELECT T.Vehicle.value('(vehiclereg)[1]', 'NVARCHAR(10)') AS vehiclereg,
       T.Vehicle.query('.'),
       GETDATE()
FROM @XmlData.nodes('vehicles/vehicle') AS T(Vehicle)

结果:

enter image description here

答案 1 :(得分:4)

根据需要进行完整查询:

DECLARE @XmlData XML
Set @XmlData = '<vehicles> 
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
</vehicles>'
SELECT T.Vehicle.value('./vehiclereg[1]', 'NVARCHAR(10)') AS vehiclereg,
       T.Vehicle.query('.'),
       GETDATE()
FROM @XmlData.nodes('/vehicles/vehicle') AS T(Vehicle)

enter image description here

答案 2 :(得分:2)

您可以在query('.')节点上XML.query()获取XML,以获取内部XML。

vehicles/vehicle

结果:

DECLARE @x XML=
'<vehicles> 
  <vehicle>
    <vehiclereg>AB12CBE</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
  <vehicle>
    <vehiclereg>AB13QQT</vehiclereg>
    <anotherprop>BLAH</anotherprop>
  </vehicle>
</vehicles>';

DECLARE @t TABLE(VehicleReg VARCHAR(128),[XML] XML,ProcessedDate DATETIME);

INSERT INTO @t(VehicleReg,[XML],ProcessedDate)
SELECT VehicleReg=n.v.value('(vehiclereg)[1]','VARCHAR(128)'),
       [XML]=n.v.query('.'),
       ProcessedDate=GETDATE()
FROM @x.nodes('vehicles/vehicle') AS n(v);

SELECT * FROM @t;