T-SQL, XQuery Invalid Column

拈花ヽ惹草 提交于 2020-01-14 13:37:09

问题


I'm just learning XQUERY and trying to accomplish what I thought would be very simple. Here's my T-SQL code:

DECLARE @XML xml
set @xml = '<resultsets><AppVersion>13.0</AppVersion></resultsets>'

-- Code below is wrong
select 
ResultSets.AppVersion.query('AppVersion').value('.', 'varchar(100)') as AppVersion
from @XML.nodes('/resultsets/AppVersion') ResultSets(AppVersion)

I cannot figure out exactly how to query that inner element, appversion. I'm not getting any errors, but I'm unable to return that 13.0 within the appversion inner-element. Can someone please help?


回答1:


You've got one AppVersion too many. This returns your 13.0 :

DECLARE @XML xml
set @xml = '<resultsets><AppVersion>13.0</AppVersion></resultsets>'

-- Code below is right
select 
ResultSets.AppVersion.value('.', 'varchar(100)') as AppVersion
from @XML.nodes('/resultsets/AppVersion') ResultSets(AppVersion)

Your nodes method already gets down to the AppVersion nodes, so from there you don't need a further query, just the value.




回答2:


If you only want one row as a result there is no need to use nodes.

DECLARE @XML xml
set @xml = '<resultsets><AppVersion>13.0</AppVersion></resultsets>'

select @XML.value('(/resultsets/AppVersion)[1]', 'varchar(100)') as AppVersion


来源:https://stackoverflow.com/questions/8590183/t-sql-xquery-invalid-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!