Skip to content

Instantly share code, notes, and snippets.

@digioz
Created June 30, 2015 22:04
Show Gist options
  • Save digioz/33ff6959e7b69e42c479 to your computer and use it in GitHub Desktop.
Save digioz/33ff6959e7b69e42c479 to your computer and use it in GitHub Desktop.
A Microsoft SQL String Split Function which returns the results as a table
CREATE FUNCTION [dbo].[fn_SplitText]
(
@RowData NVARCHAR(MAX),
@Delimeter NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE
(
ID INT IDENTITY(1,1),
Data NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @Iterator INT
SET @Iterator = 1
DECLARE @FoundIndex INT
SET @FoundIndex = CHARINDEX(@Delimeter,@RowData)
WHILE (@FoundIndex>0)
BEGIN
INSERT INTO @RtnValue (data)
SELECT
Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))
SET @RowData = SUBSTRING(@RowData,
@FoundIndex + DATALENGTH(@Delimeter) / 2,
LEN(@RowData))
SET @Iterator = @Iterator + 1
SET @FoundIndex = CHARINDEX(@Delimeter, @RowData)
END
INSERT INTO @RtnValue (Data)
SELECT Data = LTRIM(RTRIM(@RowData))
RETURN
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment