TSQL – How to find last sunday of the month

Howdy Every One.

How to get last day of any month is explained in my previous post..

Now, How to get the last sunday of any month… A little tricky isn’t it…. one of my friend went to write the loop and then tried to compare the values if it is a sunday or not from the last day of the month (by decreasing each day until he reaches a sunday)…. The method works but there is another way to do this… much simpler way….

To accomplish we need to know what day of week it is, we can get that by using dw parameter in the datepart.

Now if we know what day of the week the current input is… if the @@datefirst value is set to its default (7) then sunday will be 1 in the day of weeks.

If you subtract the number of days from seven and add it will give you the number of days between a sunday and the current date…….

Check the below code

declare @last_day_of_the_month	datetime
declare @last_sunday_of_the_month datetime
declare @input_date	datetime
set DATEFIRST 7 -- to be on the safe side
select @input_date = getdate()
select @last_day_of_the_month = dateadd(dd,datepart(dd,@input_date)*-1,dateadd(mm,1,@input_date))
select @last_sunday_of_the_month = dateadd(dd,(datepart(dw,@last_day_of_the_month)*-1)+1,@last_day_of_the_month)
select @last_sunday_of_the_month

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s