Using a CTE in a Function to Split Up a Query String

Download PDF

The question came up as to how do I parse a query string using TSQL.  So here you go, using a common table expression, and basing this on a similar function to what I put together yesterday for split.

CREATE FUNCTION dbo.SplitQueryString (@s varchar(8000))
 WITH splitter_cte AS (
 SELECT CHARINDEX('&', @s) as pos, 0 as lastPos
 SELECT CHARINDEX('&', @s, pos + 1), pos
 FROM splitter_cte
 WHERE pos > 0
 pair_cte AS (
 SELECT chunk,
 CHARINDEX('=', chunk) as pos
 SELECT SUBSTRING(@s, lastPos + 1,
 case when pos = 0 then 80000
 else pos - lastPos -1 end) as chunk
 FROM splitter_cte) as t1
 SELECT substring(chunk, 0, pos) as keyName,
 substring(chunk, pos+1, 8000) as keyValue
 FROM pair_cte

declare @queryString varchar(2048)
set @queryString = 'foo=bar&temp=baz&key=value';
 FROM dbo.SplitQueryString(@queryString)

which produces this output.

A quick and easy way to parse a query string  in TSQL using a CTE.

Posted in CTE Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


SQL Server Performance Tuning

Need help with SQL Server Performance Tuning, contact Steve at Stedman Solutions, LLC for help, or take a look at the performance tuning page at the blog. We can help with tuning a single query or with figuring out why your SQL Server is running slow. Free 30 minute consultation.

Newsletter Signup

Stay informed of Database Corruption Challenge events, and other things happening at with my newsletter.
Newsletter signup form.

Stedman Solutions