1

When adding variables to choose the month and year to query

  • @Month = 5 @Year = 2017

I want to show two columns start_day and last_day of the @month and @year

startdaymonth       lastdaymonth
=============       ============
2017-05-01           2017-05-31
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
ALDHEEB
  • 101
  • 10

4 Answers4

0

Try this:

DECLARE @Month INT = 5 
DECLARE @Year INT = 2017



SELECT DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) as FirstDate,
       DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0))) AS LastDate
Rob
  • 26,989
  • 16
  • 82
  • 98
Aswani Madhavan
  • 816
  • 6
  • 19
0
DECLARE @Month int
DECLARE @Year int

set @Month = 5
set @Year = 2017

select DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) as startdaymonth // To get the first day of the month

select DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0)))  as lastdaymonth  // To get the last day of the month
Damini Suthar
  • 1,470
  • 2
  • 14
  • 43
0

IF, you are working with SQL Server use eomonth() function for last day of specified month

declare @Month int = 2,  @Year int = 2018

select cast(concat(@month,'/',1,'/',@year) as date), eomonth(concat(@month,'/',1,'/',@year))
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
0

Try this:

;with cte as (
select cast('2017-01-01' as date) as [FirstOfMonth]
union all
select dateadd(month, 1, FirstOfMonth) from cte
where datepart(year, FirstOfMonth) < 2018
)

select FirstOfMonth,
       dateadd(day, -1, LEAD(FirstOfMonth, 1) over (order by FirstOfMonth))
from cte

First part gets you first days of all months in 2017 plus first of Jan. of 2018. Second part gets the day before, i.e. last day of the month.

Try this and you'll get better understanding :) Only thing is, that you have to exclude last record, which is 2018-01-01 :)

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69