字段需要在SQL中解析,看起来像xml

时间:2011-08-08 01:28:07

标签: xml sql-server-2008

我在sql表中有一个看起来像xml的字段。我需要解析它以获得该领域。它看起来像:

<?xml version="1.0" encoding="utf-8"?>
<Vendor>
  <Vendor_ID><![CDATA[2 RIVERS CONTRA]]></Vendor_ID>
  <Vendor_Name><![CDATA[2 RIVERS CONTRACTING & SERVICES, INC.]]></Vendor_Name>
  <Vendor_Contact><![CDATA[]]></Vendor_Contact>
  <Phone><![CDATA[0                    ]]></Phone>
  <Address><![CDATA[P.O. BOX 1512  ]]></Address>
  <City><![CDATA[ARLINGTON]]></City>
  <State><![CDATA[MA]]></State>
  <Country><![CDATA[]]></Country>
</Vendor>

我需要提取CDATA [2 RIVERS CONTRA

等字段

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

它不仅看起来像XML XML。

如果表中的列是XML数据类型列,则可以获得如下值。

select XMLCol.value('(/Vendor/Vendor_ID)[1]', 'varchar(50)') as Vendor_ID
from YourTable 

如果是varchar / nvarchar列,则需要先转换为XML。

select cast(XMLCol as xml).value('(/Vendor/Vendor_ID)[1]', 'varchar(50)') as Vendor_ID
from YourTable 

工作样本:

declare @YourTable table (XMLCol varchar(max))

insert into @YourTable values
('<?xml version="1.0" encoding="utf-8"?>
  <Vendor>
    <Vendor_ID><![CDATA[2 RIVERS CONTRA]]></Vendor_ID>
    <Vendor_Name><![CDATA[2 RIVERS CONTRACTING & SERVICES, INC.]]></Vendor_Name>
    <Vendor_Contact><![CDATA[]]></Vendor_Contact>
    <Phone><![CDATA[0                    ]]></Phone>
    <Address><![CDATA[P.O. BOX 1512  ]]></Address>
    <City><![CDATA[ARLINGTON]]></City>
    <State><![CDATA[MA]]></State>
    <Country><![CDATA[]]></Country>
  </Vendor>')

select cast(XMLCol as xml).value('(/Vendor/Vendor_ID)[1]', 'varchar(50)') as Vendor_ID
from @YourTable 

结果:

Vendor_ID
----------------
2 RIVERS CONTRA