Click here to Skip to main content
14,971,742 members
Articles / Programming Languages / SQL
Tip/Trick
Posted 18 Jul 2010

Tagged as

Stats

25.2K views
3 bookmarked

Get the last working day of the month

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
18 Jul 2010CPOL
Gets the last week day of the month
I needed a quick and dirty way of getting the last weekday of the month.

ALTER	FUNCTION [fn_LastWorkDay](
	@Date DATETIME)
RETURNS datetime

As
--Note assumes that Sunday = 1 and Saturday = 7
Begin
DECLARE
	@DW INT,
	@EOM DATETIME

	--get the last day of the month
	SET @EOM = DATEADD(hh,-1,DATEADD(mm, DATEDIFF(m,0,@Date  )+1, 0))

	--get the day of the week
	SET @DW = DATEPART(dw,@EOM)

	--make sure it is not a weekend day
	SELECT @EOM = CASE @DW WHEN 1 THEN DATEADD(d,-2,@EOM)
									WHEN 7 THEN DATEADD(d,-1,@EOM)
									ELSE @EOM END 

Return @EOM
End


Usage
SELECT dbo.fn_LastWorkDay(GETDATE())


I am confident there is a better way using nested datepart functions but this works and is simple to understand.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mycroft Holmes
Retired None
Australia Australia
Started my programming life writing Excel 1.0 macros, God what a long time ago.

Now I'm a dotnet developer, I get to influence direction, play with new toys, build stuff, life is wonderful.

Greatest buzz you can get, walk past a row of desks and see your application running on all of them (and getting paid).

Greatest irritant, pouring 12 months of knowledge and experience into an empty head only to have it leave.

Comments and Discussions

 
GeneralReason for my vote of 5 Why did you need it to be dirty? Qui... Pin
Niklas L18-Jul-10 23:42
MemberNiklas L18-Jul-10 23:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.