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