Skip to content

Instantly share code, notes, and snippets.

@karoltheguy
Last active May 9, 2017 16:31
Show Gist options
  • Save karoltheguy/791619eb9e10e106fbf1b8c6ae55146a to your computer and use it in GitHub Desktop.
Save karoltheguy/791619eb9e10e106fbf1b8c6ae55146a to your computer and use it in GitHub Desktop.
SQL Split string function
CREATE FUNCTION [dbo].[SplitString]
(
@List NVARCHAR(MAX),
@Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT
[Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(@List)
AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim)) = @Delim
) AS y
);
@karoltheguy
Copy link
Author

How to use:

SELECT *
FROM dbo.SplitString('TEST|THIS', '|')

Returns a table:

Value
1. TEST
2. THIS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment