Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 Get First and Last date for any Month in any Year

I have a stored procedure that has to accept a month as int (1-12) and a year as int. Given those two values, I have to determine the date range of that month. So I need a datetime variable to represent the first day of that month, and another datetime variable to represent the last day of that month. Is there a fairly easy way to get this info?

like image 993
Ristogod Avatar asked Oct 12 '10 15:10

Ristogod


People also ask

How do I get the start date and end date in SQL?

To use the dateadd function in SQL, we need to use the SELECT query followed by the DATEDIFF function and then return the output. The datePart should be provided only valid input (Check valid input table for datePart) and the startDate and the endDate should be provided with a date input in a proper format.

How do I get the first date of the month in SQL?

Below are the functions with logic explanation: 1. First day of current month: select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0): in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month.

How do you get the last date of the month in SQL?

The LAST_DAY() function extracts the last day of the month for a given date.


1 Answers

First day of the month: SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)

Last day of the month: SELECT DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0))

Substitute a DateTime variable value for GETDATE().

I got that long ago from this very handy page which has a whole bunch of other date calculations, such as "Monday of the current week" and "first Monday of the month".

like image 58
DOK Avatar answered Oct 25 '22 04:10

DOK