Querying XML columns in SQLServer 2005

你离开我真会死。 提交于 2019-12-13 14:28:01

问题


There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG.

<contact>
<refno>123456</refno>
<special>a piece of custom data</special>
</contact>

The tags below contact can be different for each contact, and I must query these fragments alongside the relational data columns in the same table.

I have used constructions like:

SELECT c.id AS ContactID,c.ContactName as ForeName,
c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref,    
INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid 
AND pcm.participantid=2140
WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1

This method works ok but, it takes a while for the Server to respond. I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for.

Does anyone know a better way to query XML columns??


回答1:


I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration... http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4




回答2:


If you are doing one write and a lot of reads, take the parsing hit at write time, and get that data into some format that is more query-able. A first suggestion would be to parse them into a related but separate table, with name/value/contactID columns.




回答3:


In addition to the page mentioned by @pauljette, this page has good performance optimization advice:

http://msdn.microsoft.com/en-us/library/ms345118.aspx

There's a lot you can do to speed up the performance of XML queries, but it will never be as good as properly indexed relational data. If you are selecting one document and then querying inside just that one, you can do pretty well, but when your query needs to scan through a bunch of similar documents looking for something, it's sort of like a key lookup in a relational query plan (that is, slow).




回答4:


If you have a XSD for your Xml then you can import that into your database and you can then build indexes for your Xml data.




回答5:


Try this

SELECT * FROM conversionupdatelog WHERE convert(XML,colName).value('(/leads/lead/@LeadID=''xyz@airproducts.com'')[1]', 'varchar(max)')='true'



来源:https://stackoverflow.com/questions/52084/querying-xml-columns-in-sqlserver-2005

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