THE SQL Server Blog Spot on the Web

Welcome to SQLblog.com - The SQL Server blog spot on the web Sign in | |
in Search

The Rambling DBA: Jonathan Kehayias

The random ramblings and rantings of frazzled SQL Server DBA

Using Substring() in XML FLOWR Queries

Tonight I was monitoring the #sqlhelp hashtag on Twitter for a response to a question I asked when Randy Knight (Twitter) asked a question about using SUBSTRING in FLOWR statements with XML.

#sqlhelp Is there a way to do a SQL Type "LIKE" or "SUBSTRING" in the where clause of FLWOR statement? Need to evaluate just first n chars.

By the time I posted a response, Randy had figured out how to use the contains() function to solve his problem, but I am going to blog this because I am sure that I will need this at some point in the future, and it makes for a good blog post anyway.

Using an example from the Books Online topic for FLOWR, I mocked up the following example showing how to use substring() in the where clause of a FLOWR statement.

declare @x xml
set @x='<ManuInstructions ProductModelID="1" ProductModelName="SomeBike" >
<Location LocationID="L1" >
  <Step>Manu step 1 at Loc 1</Step>
  <Step>Manu step 2 at Loc 1</Step>
  <Step>Manu step 3 at Loc 1</Step>
</Location>
<Location LocationID="L2" >
  <Step>Manu step 1 at Loc 2</Step>
  <Step>Manu step 2 at Loc 2</Step>
  <Step>Manu step 3 at Loc 2</Step>
</Location>
</ManuInstructions>'
SELECT @x.query('
   for $step in /ManuInstructions/Location[1]/Step
   where substring(string($step), 11, 1) = "2"
   return string($step)
')

This outputs only a single node value where the substring() function evaluation matches the string value of 2.

Published Monday, January 24, 2011 11:41 PM by Jonathan Kehayias

Comments

 

AllenMWhite said:

You could also use the XQuery .exists method combined with the contains clause to check for a match.

January 24, 2011 10:57 PM
Anonymous comments are disabled

This Blog

Syndication

Powered by Community Server (Commercial Edition), by Telligent Systems
  Privacy Statement