SQL变量月份为隐蔽日期

时间:2017-12-20 06:45:12

标签: mysql sql

添加变量以选择要查询的月份和年份

  • @Month = 5 @Year = 2017

我想显示@month和@year

的两列start_day和last_day
startdaymonth       lastdaymonth
=============       ============
2017-05-01           2017-05-31

4 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分: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

答案 2 :(得分:0)

IF ,您正在使用SQL Server使用eomonth()函数指定月份的最后一天

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

select cast(concat(@month,'/',1,'/',@year) as date), eomonth(concat(@month,'/',1,'/',@year))

答案 3 :(得分:0)

试试这个:

;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:)