2014-02-26 69 views
0

我在数据库表中存储了以下xml。在sql查询中提取xml元素

我想从xml中提取Productid,我一直不成功。 你能告诉我为了使查询工作需要做什么改变吗?

XML:

DECLARE @Response VARCHAR(MAX) = '<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<ProductId xsi:type="xsd:long" xmlns="http://nn.service.eservice_v1">30061</ProductId> 
</Response>' 

SQL查询:

select 
CONVERT(XML,CONVERT(NVARCHAR(max),@Response)).value('(/Response/ProductId)[1]','nvarchar(500)') as ProviderId 

回答

0

要存储在XML中的XML类型,而不是从varchar转换。如果你能删除所有的命名空间的东西,下面的工作。

DECLARE @Response XML = '<Response><ProductId>30061</ProductId></Response>' 

SELECT @Response.value('(//ProductId)[1]','nvarchar(500)') as ProviderId 

如果您不能去掉所有的命名空间的东西,那么你就需要包含WITH XMLNAMESPACES子句

DECLARE @Response XML = '<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<ProductId xsi:type="xsd:long" xmlns="http://nn.service.eservice_v1">30061</ProductId> 
</Response>' 

;WITH XMLNAMESPACES ('http://nn.service.eservice_v1' as e, 
      'http://www.w3.org/2001/XMLSchema-instance' as xsi) 
SELECT @Response.value('(/Response/e:ProductId)[1]','nvarchar(500)') as ProviderId