Question

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!

Was it helpful?

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

OTHER TIPS

-- Try this

Select CHARINDEX('W', 'HHWHHWHWWWHHWWWWWHHWWWWWHHWWWWW') AS FirstWorkingDay,
LEN('HHWHHWHWWWHHWWWWWHHWWWWWHHWWWWW') - CHARINDEX('W', REVERSE('HHWHHWHWWWHHWWWWWHHWWWWWHHWWWWW')) -1  AS LastWorkingDay

Try this:

MySQL

@month_col = 'HHWHHWHWWWHHWWWWWHHWWWWWHHWWHHH' 

Locate character from starting of string

SELECT LOCATE('W', @month_col);

OUTPUT: 3

Locate character from end of the string

SELECT LENGTH(@month_col) + 1 - LOCATE('W', REVERSE(@month_col));

OUTPUT: 28


SQL SERVER

@month_col = 'HHWHHWHWWWHHWWWWWHHWWWWWHHWWHHH' 

Locate character from starting of string

SELECT CHARINDEX('W', @month_col, 0);

OUTPUT: 3

Locate character from end of the string

SELECT LEN(@month_col) + 1 - CHARINDEX('W', REVERSE(@month_col), 0);

OUTPUT: 28

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top