Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last Monday of the current month using T-sql

I know this is quite a generic question but does anyone know a good way of checking if the date is the last monday of the month using T-SQL. I need to use it in a stored procedure to determine if the stored procedure returns data or does nothing.

Cheers!

like image 620
nick gowdy Avatar asked Jan 17 '23 08:01

nick gowdy


1 Answers

The following select will return 1 if the current date is the last monday of the month, and 0 if not.

select 
 case 
 when datepart(dw, GETDATE()) = 2 and DATEPART(month, DATEADD(day, 7, GETDATE())) <> DATEPART(month, GETDATE())
 then 1
 else 0
 end

datepart(dw, GETDATE()) returns the day of the week. Monday is 2. The second part adds 7 days to the current date and checks that within 7 days the month has changed (if it does not, it is not the last monday).

Change the GETDATE()'s to any date you want to check.

EDIT:

You can make it into a generic function and use it with any date you like:

CREATE FUNCTION 
IsLastMondayOfMonth(@dateToCheck datetime)
RETURNS bit
AS
BEGIN
DECLARE
@result bit

SELECT @result =
    CASE  
       WHEN datepart(dw, @dateToCheck) = 2 AND DATEPART(month, DATEADD(day, 7, @dateToCheck)) <> DATEPART(month, @dateToCheck)
    THEN 1
 ELSE 0
 END
 RETURN @result
END
like image 174
Klaus Byskov Pedersen Avatar answered Jan 31 '23 21:01

Klaus Byskov Pedersen