Printed 2017/08/16 08:01AM

SQLBIGeek’s Function Friday – Return Last Date of the Prior Month

By Brian K. McDonald, 2010/11/05



Brian K. McDonald

Brian K. McDonald


Twitter: @briankmcdonald


Welcome to the fourth post of my “SQLBIGeek’s Function Friday” blog series. In this series, I am hoping that I can provide some of the details about functions that I have either found on the internet or something that I had to create to meet a need. If it is something that I come across, I will attempt to make it shorter and/or perform better. If it is something I wrote, it is just something to share with you J Either way, I hope that you enjoy the series and that you can get some useful ideas or functions to use in your environment.



I can’t remember what I used this for when I created it, but I thought that I would share it none-the-less. Somewhat related to my prior blog on getting the first day of month, this can be used to get the last day of the prior month based on whatever date that is passed into the function.


Script 1: Function

CREATE FUNCTION [dbo].[ufn_LastDayOfPriorMonth]




Created By: Brian K. McDonald, MCDBA, MCSD (


Twitter:    @briankmcdonald

Date:       10/29/2010

Purpose:    Return the last day of the prior month based on date

            passed into the function


Usage:      SELECT dbo.ufn_LastDayOfPriorMonth ('10/29/2010')


Modification History










      SET @LastDayOfPriorMonth = DATEADD(d,(-1*DATEPART(d,CONVERT(VARCHAR(12),@Date,101))),CONVERT(VARCHAR(12),@Date,101))

      RETURN @LastDayOfPriorMonth





--A few sample executions

SELECT AdventureWorks.dbo.ufn_LastDayOfPriorMonth('1/10/2010')    --returns 12/31/2009

SELECT AdventureWorks.dbo.ufn_LastDayOfPriorMonth('6/15/2010')    --returns 5/31/2010

SELECT AdventureWorks.dbo.ufn_LastDayOfPriorMonth('10/29/2010')   --returns 9/30/2010

SELECT AdventureWorks.dbo.ufn_LastDayOfPriorMonth('11/29/2010')   --returns 10/31/2010


--Clean up

DROP FUNCTION dbo.ufn_LastDayOfPriorMonth


Please be sure to return for the next BISQLGeek's Function Friday! I hope that you have enjoyed this post. If you did, please take just a moment to rate it below! Also, if you don’t already, please be sure to follow me on twitter at @briankmcdonald. Also note that you can subscribe to an RSS feed of my blogs.



Brian K. McDonald, MCDBA, MCSD
Business Intelligence Consultant – Pragmatic Works

Email: | Blogs: SQLBIGeek | SQLServerCentral | BIDN

Twitter: @briankmcdonald | LinkedIn:

 ** Corrected Content 11/11/2010 **


Copyright © 2002-2017 Redgate. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.