Created
October 17, 2012 19:45
-
-
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
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 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