Skip to content

Instantly share code, notes, and snippets.

@bencoveney
Created September 29, 2014 12:09
Show Gist options
  • Save bencoveney/ec0e0568bd8877139345 to your computer and use it in GitHub Desktop.
Save bencoveney/ec0e0568bd8877139345 to your computer and use it in GitHub Desktop.
Parsing comma seperated values using SQL CTEs
WITH
/* Provides the seed CSV to parse, can be selected from a table */
CSVRoot AS (
SELECT
'5,8,3,55,2' + ',' AS CSV,
LEN('5,8,3,55,2' + ',') AS Length,
NULL AS Number
),
CSVParser AS (
/* Includes all previous data from the previous layer of recursion */
SELECT
CSV,
Length,
Number
FROM
CSVRoot
UNION ALL
/* Takes the number from the front of the csv */
SELECT
/* Preserves everything to the right of the first comma (the bits left to parse) */
RIGHT(Recurse.CSV, LEN(Recurse.CSV) - CHARINDEX(',', Recurse.CSV)) AS CSV,
/* Calculates how long the remaining CSV is (which is used for termination) */
LEN(RIGHT(Recurse.CSV, LEN(Recurse.CSV) - CHARINDEX(',', Recurse.CSV))) AS Length,
/* Takes the number to the left of the first comma and casts it */
CAST(LEFT(Recurse.CSV, CHARINDEX(',', Recurse.CSV) - 1) AS INT) AS Number
FROM
CSVParser AS Recurse
WHERE
/* Recursion termination (only recurse when theres stuff in the CSV left to parse) */
Length > 0
)
/* Query the CSV Parser */
SELECT
MIN(Number) AS LowestValue,
MAX(Number) AS HighestValue
FROM
CSVParser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment