Created
February 18, 2019 21:50
-
-
Save adamdehaven/440bd43fe3fac046a6127407882df24c to your computer and use it in GitHub Desktop.
SQL Function to split a comma-delimited string into a table result
This file contains hidden or 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
CREATE FUNCTION [dbo].[SplitCommaDelimitedString] | |
( | |
@string NVARCHAR(MAX), | |
@delimiter CHAR(1) | |
) | |
RETURNS @output TABLE(splitdata NVARCHAR(MAX) | |
) | |
BEGIN | |
DECLARE @start INT, @end INT | |
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) | |
WHILE @start < LEN(@string) + 1 BEGIN | |
IF @end = 0 | |
SET @end = LEN(@string) + 1 | |
INSERT INTO @output (splitdata) | |
VALUES(SUBSTRING(@string, @start, @end - @start)) | |
SET @start = @end + 1 | |
SET @end = CHARINDEX(@delimiter, @string, @start) | |
END | |
RETURN | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment