Created
February 23, 2015 19:54
-
-
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
This file contains 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].[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