[英]verify that xml node has a child node with a given value tsql
I have the following tables 我有以下表格
A (ID, relatedID, typeId )
B (ID, leftID, leftTypeId)
I want to join the two tables like this 我想加入这样的两个表
select * from A
inner join B on A.TypeId=B.LeftTypeId and {condition}
where condition should verify id the leftID would match a value from relatedID , where relatedId is a xml column. where 条件应该验证id, leftID将匹配来自relatedID的值,其中relatedId是xml列。 Eg.
例如。 relatedID=
<Id>1</Id>
relatedID =
<Id>1</Id>
Is there a optimal way to do this? 有最佳方法吗?
UPDATE relatedID
can contain several Ids. UPDATE
relatedID
可以包含多个ID。 Eg Eg. 例如,例如。
relatedID=<Id>1</Id><Id>2</Id>
You may use 你可以用
... and A.relatedID.value('(/Id[1]/text())[1]', 'int') = B.leftID
or 要么
... and A.relatedID.exist('(/Id[1]/text())[1] = sql:column("B.leftID")') = 1
Though exist
is recommended over value
for predicates, depending on whether the XML
column is xml-indexed or not and what type of indexes it has, one of the two above may perform better. 虽然建议
exist
超过谓词的value
,但取决于XML
列是否为xml索引以及它具有哪种类型的索引,上述两个中的一个可能表现更好。
upd. UPD。 for the case when relatedID can contain set of Ids you may try
对于relatedID可以包含一组ID的情况,您可以尝试
select ...
from A
cross apply A.relatedID.nodes('/Id') r(id)
inner join B on A.TypeId=B.LeftTypeId
and r.id.value('text()[1]', 'int') = B.leftID
or 要么
select ...
from A
cross apply A.relatedID.nodes('/Id') r(id)
inner join B on A.TypeId=B.LeftTypeId
and r.id.exist('text()[1]=sql:column("B.leftID")') = 1
or even 甚至
select ...
from A
inner join B on A.TypeId=B.LeftTypeId
and A.relatedID.exist('/Id[text()[1]=sql:column("B.leftID")]') = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.