Search

Saturday, August 27, 2011

Function to Get Specific Part of String

SUBSTRING is a good function to get a part of string, but when a string consists of many parts, getting specific part of it, is a bit painful task. Hopefully, following function will help you to achieve such tasks. 


The 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.fn_GetPartString('First,Second,Third,Forth,Fifth',3,',')


CREATE FUNCTION dbo.fn_GetPartString
(
            @StrTemp NVARCHAR(1000),
            @Section SMALLINT,
            @Separator NCHAR(1)


RETURNS NVARCHAR(2000)
BEGIN
      DECLARE
                  @StartPos INT,
                  @EndPos INT,
                  @Cycle INT,
                  @Result NVARCHAR(1000)


            SELECT @Cycle = 0,
                        @StartPos = 0
                        WHILE @Cycle < @Section-1
                              BEGIN
                                    SELECT @StartPos =    
                                    CHARINDEX(@Separator,@StrTemp,@StartPos)+1
                                    IF @StartPos = 1
                                          SELECT @Cycle = @Section
                                    ELSE                                           
                                          SELECT @Cycle = @Cycle + 1
                              END
            SELECT @EndPos  = CHARINDEX(@Separator,@StrTemp,@StartPos)
            SELECT @Result = LTRIM(RTRIM(SUBSTRING(@StrTemp,@StartPos,
                    CASE @EndPos WHEN 0 THEN (LEN(@StrTemp)+1)-@StartPos
                    ELSE (@EndPos-@StartPos) END)))
        RETURN @Result
END

No comments:

Post a Comment