在SQL Server 2014中查询XML数据

时间:2017-07-29 23:37:22

标签: sql-server xml

使用下面的代码,我试图将一个xml文档引入SQL Server Management Studio。代码运行但在结果页面中,行数据以全部NULL的形式出现。这是代码:

declare @xml xml

select @xml=d
from openrowset (bulk 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\NYairData.xml', single_blob) as data(d)

declare @hdoc int

exec sp_xml_preparedocument @hdoc output, @xml

select *
from openxml (@hdoc,'response/row/row',1)
with (
    _id varchar(100),
    indicator_data_id int,
    indicator_id int,
    measure varchar(1000),
    geo_type_name varchar(200),
    geo_entity_id int,
    geo_entity_name varchar(100),
    year_description int,
    data_valuemessage float)

exec sp_xml_removedocument @hdoc

这里是我尝试使用的一些xml数据:

<response>
   <row>
     <row _id="1" _uuid="FDE5AC30-B86A-47C5-9A82-9333398F7898" _position="1" _address="http://data.cityofnewyork.us/resource/c3uy-2p5r/1">
        <indicator_data_id>130728</indicator_data_id>
        <indicator_id>646</indicator_id>
        <name>
            Air Toxics Concentrations- Average Benzene Concentrations
        </name>
        <measure>Average Concentration</measure>
        <geo_type_name>Borough</geo_type_name>
        <geo_entity_id>1</geo_entity_id>
        <geo_entity_name>Bronx</geo_entity_name>
        <year_description>2005</year_description>
        <data_valuemessage>2.8</data_valuemessage>
     </row>

该数据来自纽约开放数据网站。以下是源网站的链接:https://data.cityofnewyork.us/Environment/Air-Quality/c3uy-2p5r。我是将数据引入DBMS的新手。以下是输出的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:1)

阅读OPEN XML文档并查看其中的示例。

另一个好读:XML Elements vs. Attributes

select *
from openxml (@hdoc,'response/row/row',2) -- 2 = Use the element-centric mapping.
with (
    _id varchar(100) './@_id', -- ColPattern to map _id attribute
    indicator_data_id int,
    indicator_id int,
    measure varchar(1000),
    geo_type_name varchar(200),
    geo_entity_id int,
    geo_entity_name varchar(100),
    year_description int,
    data_valuemessage float)