从xml列中检索属性值

时间:2013-01-21 07:09:40

标签: sql sql-server-2008

<storage xmlns="http://energy" created-on="2013-01-21T05:00:15Z">
<country>Italy</country>
<Points>
    <point>Callato;Cellino</point>
</Points>
    </storage>

上面的数据是一个表中的列(xmlcolumn),用于从上面单独检索单独创建的表。当我使用下面的查询时,我将变为空

 SELECT
 OutputXML.value('(storage/@created-on)[1]','date') 
  AS ProductType,*
FROM [DataOutput];

我正在做的错误是什么,谢谢Arun

1 个答案:

答案 0 :(得分:0)

您需要为查询指定命名空间:

declare @t table (a xml)
insert into @t(a) values ('<storage xmlns="http://energy" created-on="2013-01-21T05:00:15Z">
<country>Italy</country>
<Points>
    <point>Callato;Cellino</point>
</Points>
    </storage>')

 SELECT
 a.value('declare namespace x = "http://energy";
          (x:storage/@created-on)[1]','date') 
  AS ProductType,*
FROM @t;

为了便于阅读,我将其拆分为两行。但是,没有必要这样做。

结果:

ProductType a
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2013-01-21  <storage xmlns="http://energy" created-on="2013-01-21T05:00:15Z"><country>Italy</country><Points><point>Callato;Cellino</point></Points></storage>