我很久以来一直在解决这个问题,似乎已经接近成功了,但还差一点点就能够达成目标。我的数据库中有一个列,看起来像这样:
<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>
在这个例子中,我需要查询并返回“two是第二个数字”。我也想在不创建临时表的情况下做到这一点。目前我的代码如下:
create table #test (item1 xml)
insert into #test (item1)
values ('<document> <items> <item name="one">one is the first number</item> <item name="two">two is the second number</item> </items> </document>')
select item1.value('(/document/items/item)[2]', 'nvarchar(max)') from #test
select item1.query('/document/items/item[@name="two"]') from #test
第一个select返回了正确的值,但我需要知道它是第二个“index”。第二个select返回了我想要的内容,但它返回了整个节点two。我错过了什么?是否有一种简单的方法可以使用XML而不需要转换为临时表?