substring Function (XQuery)
Returns part of the value of $sourceString, starting at the position indicated by the value of $startingLoc, and continues for the number of characters indicated by the value of $length.
The three-argument version of the function returns the characters in $sourceString whose position $p obeys:
fn:round($startingLoc) <= $p < fn:round($startingLoc) + fn:round($length)
The value of $length can be greater than the number of characters in the value of $sourceString following the start position. In this case, the substring returns the characters up to the end of $sourceString.
The first character of a string is located at position 1.
If the value of $sourceString is the empty sequence, it is handled as the zero-length string. Otherwise, if either $startingLoc or $length is the empty sequence, the empty sequence is returned.
Supplementary Characters (Surrogate Pairs)
The behavior of surrogate pairs in XQuery functions depends on the database compatibility level and, in some cases, on the default namespace URI for functions. For more information, see the section "XQuery Functions Are Surrogate-Aware" in the topic Breaking Changes to Database Engine Features in SQL Server 2012. Also see ALTER DATABASE Compatibility Level (Transact-SQL) and Collation and Unicode Support.
This topic provides XQuery examples against XML instances stored in various xml type columns in the AdventureWorks2012 database.
A. Using the substring() XQuery function to retrieve partial summary product-model descriptions
The query retrieves the first 50 characters of the text that describes the product model, the <Summary> element in the document.
WITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS pd)
SELECT ProductModelID, CatalogDescription.query('
<Prod>{ substring(string((/pd:ProductDescription/pd:Summary)[1]), 1, 50) }</Prod>
') as Result
FROM Production.ProductModel
where CatalogDescription.exist('/pd:ProductDescription') = 1;
Note the following from the previous query:
-
The string() function returns the string value of the<Summary> element. This function is used, because the <Summary> element contains both the text and subelements (html formatting elements), and because you will skip these elements and retrieve all the text.
-
The substring() function retrieves the first 50 characters from the string value retrieved by the string().
This is a partial result:
ProductModelID Result -------------- ---------------------------------------------------- 19 <Prod>Our top-of-the-line competition mountain bike.</Prod> 23 <Prod>Suitable for any type of riding, on or off-roa</Prod> ...