[英]Parse / query XML using TSQL
我已經打了一段時間,似乎我很接近,但不是那里。 我在數據庫中有一個列如下所示:
<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>
在這個例子中,我需要查詢並返回'two is the second number'。 我也想在不創建臨時表的情況下這樣做。 目前我有:
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
第一個選擇返回正確的值,但我需要知道它是第二個'索引'第二個返回我想要的但它返回整個節點兩個..
我錯過了什么? 並且,有沒有一種簡單的方法來使用XML而無需轉換為臨時表?
我也想在不創建臨時表的情況下這樣做
您可以使用數據類型為XML的變量。
declare @xml xml
set @xml =
'<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>'
select @xml.value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')
或者,您可以在查詢中將字符串轉換為XML。
select cast(
'<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>' as xml
).value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')
您的第一個查詢使用正確的.value()
,第二個查詢具有正確的XQuery表達式。 使用.value()
您需要使用返回單個值的XQuery表達式。 這將為您提供所有項目節點,其中@name
為2 /document/items/item[@name="two"])
。 最后添加[1]
可確保只在@name
為2的XML中出現第一個匹配項。
(首先,不是臨時表,你可以使用xml
類型的變量,如下所示。這些變量可以直接從字符串文字中分配)
所以我認為你的意思是你想要name
two
的item
節點的文本值,在這種情況下你只需要在你在value()
調用中使用的xpath中包含適當的條件:
DECLARE @x xml
SET @x = '<document> <items> <item name="one">one is the first number</item>
<item name="two">two is the second number</item> </items> </document>'
SELECT @x.value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')
給
--------------------------------------------------------------
two is the second number
(1 row(s) affected)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.