How to get last date of particular month from the month ID and year in SQL ?
Inputs :
@MonthID INT = 2,
@Year INT = 2015
Required output : 28/02/2015
How to get last date of particular month from the month ID and year in SQL ?
Inputs :
@MonthID INT = 2,
@Year INT = 2015
Required output : 28/02/2015
It's easy in SQL Server 2012+
To frame date from the year and month use DATEFROMPARTS (Transact-SQL)
To find the last day of month use EOMONTH (Transact-SQL)
Declare @MonthID INT = 2,
@Year INT = 2015
SELECT Eomonth(Datefromparts(@Year, @MonthID, 1))
For any thing less then Sql server 2012
SELECT Dateadd(dd, -1, Dateadd(mm, 1, Cast(Cast(@Year AS CHAR(4)) + '-'
+ Cast(@MonthID AS VARCHAR(2))+'-'+'1' AS DATE)))
Note: If the variables are of Varchar
type then you can remove the cast
to varchar
You can find the last day of the month in the following manner
Declare @MonthID varchar(10) = '02', @Year varchar(10) = '2015'
select dateadd(dd,-1,dateadd(MM,1,cast(@Year+'-'+@MonthID+'-1' as date)))
This is how I did it.
DECLARE @MonthID INT = 3,
@Year INT = 2015
DECLARE @InputDate DATE, @TempDate DATE, @OutputDate DATE
SET @InputDate = CAST(CAST(@Year AS VARCHAR) + '-' + CAST(@MonthID AS varchar) + '-01' AS DATE)
SET @TempDate = @InputDate
WHILE (DATEPART(m, @InputDate) = DATEPART(m, @TempDate))
BEGIN
SET @OutputDate = @TempDate
SET @TempDate = DATEADD(d,1,@TempDate)
END
SELECT @OutputDate