SQL Server - XQuery for XML

风格不统一 提交于 2019-12-20 05:49:17

问题


Just similar other post, I need to retrieve any rows from table applying criteria on Xml column, for instance, supposing you have an xml column like this:

<DynamicProfile xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WinTest">
  <AllData xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:KeyValueOfstringstring>
      <d2p1:Key>One</d2p1:Key>
      <d2p1:Value>1</d2p1:Value>
    </d2p1:KeyValueOfstringstring>
    <d2p1:KeyValueOfstringstring>
      <d2p1:Key>Two</d2p1:Key>
      <d2p1:Value>2</d2p1:Value>
    </d2p1:KeyValueOfstringstring>
  </AllData>
</DynamicProfile>

My query would be able to return all rows where node value <d2p1:Key> = 'some key value' AND node value <d2p1Value = 'some value value'.

Imagine of that just as a dynamic table where KEY node represent the column name and Value node represent column's value.

The following query does not work because key and value nodes are not sequential:

select * from MyTable where
MyXmlField.exist('//d2p1:Key[.="One"]') = 1
AND MyXmlField.exist('//d2p1:Value[.="1"]') = 1 

回答1:


Instead of looking for //d2p1:key[.="One"] and //d2p1:Value[.="1"] as two separate searches, do a single query that looks for both at once, like so:

//d2p1:KeyValueOfstringstring[./d2p1:Key="One"][./d2p1:Value=1]



来源:https://stackoverflow.com/questions/10519701/sql-server-xquery-for-xml

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