Skip to content

Instantly share code, notes, and snippets.

@sotirisf
Created February 23, 2015 19:54
Show Gist options
  • Save sotirisf/33dbf9cd67d8919670fc to your computer and use it in GitHub Desktop.
Save sotirisf/33dbf9cd67d8919670fc to your computer and use it in GitHub Desktop.
UDF that gets a delimited string and returns a table variable with the values of the string as rows
CREATE Function [dbo].[fn_ParseDelimitedStrings]
(
@String nvarchar(max),
@Delimiter char(1)
)
Returns @Values Table
(
RowId int Not Null Identity(1,1) Primary Key,
Value nvarchar(3000) Not Null
)
As
Begin
Declare @startPos smallint,@endPos smallint
If (Right(@String, 1) != @Delimiter)
Set @String = @String + @Delimiter
Set @startPos = 1
Set @endPos = CharIndex(@Delimiter, @String)
While @endPos > 0
Begin
Insert @Values(Value)
Select LTrim(RTrim(SubString(@String, @startPos, @endPos - @startPos)))
-- remove the delimiter just used
Set @String = Stuff(@String, @endPos, 1, '')
-- move string pointer to next delimiter
Set @startPos = @endPos
Set @endPos = CharIndex(@Delimiter, @String)
End
Return
End
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment