Search code examples
mysqlsql-serverselectlocatecharindex

Get index of first occurence of char in string from the end in t-sql


I'd appreciate any help

I have a string representing working days and days off of one month:

 @month_col = 'HHWHHWHWWWHHWWWWWHHWWWWWHHWWWWW' -- H - Holiday, W-Working day, total 31 days

I need to get the index of last working day in the current month, which is in this case 31.

Or if

@month_col = 'HHWHHWHWWWHHWWWWWHHWWWWWHHWWHHH' 

Then the last wotking day is 28.

I know how to get the first working day:

--FIRST WORKING DAY OF MONTH
    WHILE @index<= @len
     BEGIN
     set @char = SUBSTRING(@month_col, @index, 1)
     IF @char = 'W' 
     begin
        select @first_day = CHARINDEX(@char, @month_col)
        break
     end
    SET @index= @index+ 1   
    END

So, what about last one? I tried to iterate reversely but getting NULL. Thanks in advance!


Solution

  • Reverse the string.

    SET @Reversed = Reverse(@month_col);
    WHILE @index<= @len
     BEGIN
     set @char = SUBSTRING(@Reversed, @index, 1)
     IF @char = 'W' 
     begin
        select @first_day = CHARINDEX(@char, @Reversed)
        break
     end
     SET @index= @index + 1
    END
    SET @lastday= @len - @first_day + 1   
    

    EDIT: I think your original code can be much simpler. There's no need for the loop, use CHARINDEX and that's it.

    SELECT @first_day = CHARINDEX('W', @month_col, 1)
    

    My code would look like this:

    SELECT @first_day = CHARINDEX('W', REVERSE(@month_col), 1)
    SET @lastday= @len - @first_day + 1