添加变量时选择要查询的月份和年份
我想显示@month和@year的两列start_day和last_day
startdaymonth lastdaymonth
============= ============
2017-05-01 2017-05-31
试试这个:
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
如果您正在使用SQL Server使用eomonth()
函数指定月份的最后一天
declare @Month int = 2, @Year int = 2018
select cast(concat(@month,'/',1,'/',@year) as date), eomonth(concat(@month,'/',1,'/',@year))
试试这个:
;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
第一部分为您提供2017年所有月份的第一天以及2018年1月的第一天。第二部分获取前一天,即该月的最后一天。
尝试这个,你会得到更好的理解:)唯一的事情是,你必须排除最后的记录,这是2018-01-01 :)
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