Created
August 28, 2018 13:29
-
-
Save ukcoderj/36be236b6803363aefc7020b4260a20c to your computer and use it in GitHub Desktop.
SQL Split String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Converts a delimited string to a table | |
Works on old versions of sql (2016, has string splitting functionality) | |
e.g. SplitString 'A,B,C', ',' | |
-> Id, Data | |
1 A | |
2 B | |
3 C | |
*/ | |
CREATE FUNCTION SplitString | |
( | |
@String NVARCHAR(4000), | |
@Delimiter NCHAR(1) | |
) | |
RETURNS TABLE | |
AS | |
RETURN | |
( | |
WITH Split(stpos,endpos) | |
AS( | |
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos | |
UNION ALL | |
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1) | |
FROM Split | |
WHERE endpos > 0 | |
) | |
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)), | |
'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos) | |
FROM Split | |
) | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment