I am using SQL Server 2008 Enterprise + VSTS 2008 + C# + .Net 3.5 + ASP.Net + IIS 7.0 to develop a simple web application. In my database table, I have a XML type column. The content is like below,
I want to get AdditionalInfoList of all rows in the table if Title contains “software engineer” or Info contains “Software Development”. My question is how to write such query efficiently?
<People>
<Item Name="Username" Value="George" />
<Item Name="Info" Value="Software Development Information" />
<Item Name="Title" Value="Software Engineer in Backend" />
<AdditionalInfoList>
<AdditionalInfoListItem Guid="xxx" type="type1" />
<AdditionalInfoListItem Guid="yyy" type="type2" />
</AdditionalInfoList>
</People>
You need to do something like this:
That should give you all the entries you’re interested in.
Explanations:
The
CROSS APPLYcreates a “dummy” table which you need to give a name to – here:Tbl(People). What that name is doesn’t really matter, and it’s not case sensitive, soTblandtblare identical.If you want to Guid and the type as separate values from the
<AdditionalInfoList>, you need to use this query here:You basically have to do a second CROSS APPLY (that’ll hurt your performance!) to get the “additional info” list for each of the entries from
Tbl.Personand extract the Guid and the type value from that.Check out the SQL Server 2005 XQuery and XML DML introduction – about in the middle of the article, there’s a section on how to use the
.nodes()function. Very helpful!