![](/img/trans.png)
[英]How to add attributes to an existing xml string stored as a field from the rest of the columns in the same row using SQL
[英]How can I get and compare two XML attributes using TSQL where the XML string is stored in a field?
我正在使用SQL Server 2008 R2。
想象一下一張桌子:
id | contentXml
1 | <node attr1='a' attr2='b' attr3='a'/>
2 | <node attr1='a' attr2='b' attr3='c'/>
3 | <node attr3='c' attr2='d' attr1='c'/>
預期結果應該是ID的列表,其中attr1和attr3的值相同。 請注意,屬性的順序可能與上面的示例不同。
結果:1和3
我認為最快的方法是使用sqlxml exists()方法:
select
t.id
from Table1 as t
where t.contentXml.exist('node[@attr1 = @attr3]') = 1
使用sqlxml value()也可以這樣做:
select
t.id
from Table1 as t
where
t.contentXml.value('(node/@attr1)[1]', 'varchar(max)') =
t.contentXml.value('(node/@attr3)[1]', 'varchar(max)')
但這個會慢一些。
在這里你有一個不同的方法:
SELECT id,
t.contentXml.value('(/node/@attr1)[1]','nvarchar(max)'),
t.contentXml.value('(/node/@attr3)[1]','nvarchar(max)')
FROM Table1 t
WHERE t.contentXml.value('(/node/@attr1)[1]','nvarchar(max)') = t.contentXml.value('(/node/@attr3)[1]','nvarchar(max)')
並在SQL Fiddle上運行sql代碼
結果:
id
1 a a
3 c c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.