Skip to content

Instantly share code, notes, and snippets.

@lionofdezert
Created October 17, 2012 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lionofdezert/3907687 to your computer and use it in GitHub Desktop.
Save lionofdezert/3907687 to your computer and use it in GitHub Desktop.
Function takes a string and section number of string which is required and separator, which separates different sections of given string
--| Create By: Aasim Abdullah
--| Description: Function takes a string and section number of string which
--| is required and separator, which separates different
--| sections of given string
--| How To Use: SELECT dbo.usp_stringpart('First,Second,Third,Forth,Fifth',3,',')
CREATE FUNCTION dbo.usp_stringpart
(
@InputString NVARCHAR(1000),
@Section SMALLINT,
@Separator NCHAR(1)
)
RETURNS NVARCHAR(1000)
BEGIN
DECLARE @StartPosition INT,
@EndPosition INT,
@Cycle INT,
@ResultString NVARCHAR(1000)
SELECT @Cycle = 0,
@StartPosition = 0
WHILE @Cycle < @Section - 1
BEGIN
SELECT @StartPosition = CHARINDEX(@Separator, @InputString,
@StartPosition) + 1
IF @StartPosition = 1
SELECT @Cycle = @Section
ELSE
SELECT @Cycle = @Cycle + 1
END
SELECT @EndPosition = CHARINDEX(@Separator, @InputString, @StartPosition)
SELECT @ResultString = LTRIM(RTRIM(SUBSTRING(@InputString, @StartPosition,
CASE @EndPosition
WHEN 0
THEN ( LEN(@InputString)
+ 1 )
- @StartPosition
ELSE ( @EndPosition
- @StartPosition )
END)))
RETURN @ResultString
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment