Skip to content

Instantly share code, notes, and snippets.

@klimaye
Created December 27, 2013 13:56
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save klimaye/8147193 to your computer and use it in GitHub Desktop.
Save klimaye/8147193 to your computer and use it in GitHub Desktop.
sql scaler function to return an item at a specific index in a split string. Was useful to me in a select clause parsing a value like Age_0_14
CREATE FUNCTION dbo.itemAtIndexInASplitString( @stringToSplit VARCHAR(MAX), @delimiter VARCHAR(5), @indexToReturn int)
RETURNS
varchar(max)
AS
BEGIN
DECLARE @returnList TABLE ([ID] int, [Name] [nvarchar] (500))
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
DECLARE @index INT
DECLARE @return_value varchar(max)
SET @index = 0
SET @return_value = null
WHILE CHARINDEX(@delimiter, @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX(@delimiter, @stringToSplit)
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)
INSERT INTO @returnList
SELECT @index, @name
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
SET @index = @index + 1
END
INSERT INTO @returnList
SELECT @index, @stringToSplit
SELECT @return_value = Name from @returnList where [ID] = @indexToReturn
RETURN @return_value
END
GO
@Gardoglee
Copy link

Thanks! This is exactly what I needed. Referred here via your response on StackOverflow.

@vibs2006
Copy link

@klimaye how to find last index of input string?

@dramirz
Copy link

dramirz commented Jul 1, 2021

Thanks!

@acanalesg
Copy link

acanalesg commented Jan 29, 2022

Love it, thanks! Can't understand why there is no buit-in function for this

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