日期比较和差异

时间:2020-03-04 01:35:05

标签: sql sql-server ssms

我有带有员工“ StartDate”的“ Employee”表。

我想获得下个月即将迎来工作周年纪念日的所有员工的名单。

到目前为止,我已经达到了这一点:

SELECT *
FROM Employee
WHERE DATEDIFF(DAY, DAY(StartDate), DAY(GETDATE())) = 30

...但这似乎不起作用。

2 个答案:

答案 0 :(得分:3)

我想获得下个月即将迎来工作周年纪念日的所有员工的名单。

首先找到下个月的日期

DATEADD(MONTH, 1, GETDATE())

然后找到下个月StartDate的员工

SELECT *
FROM   Employee
WHERE  DATEPART(MONTH, StartDate) = DATEPART(MONTH, DATEADD(MONTH, 1, GETDATE()))

答案 1 :(得分:0)

类似的功能将起作用。不过,where子句中的函数可能会导致大型数据集出现问题:

declare     @day int = day(getdate())
            ,@month int = month(getdate())

if @month = 12 set @month = 1
else set @month = @month +1

SELECT 
    [columns]
  FROM [table]
where day(Startdate) = @day
and MONTH(Startdate) = @month

或者如果您不在乎一天(我想您可能不在意),那么:

declare @month int = month(getdate())

if @month = 12 set @month = 1
else set @month = @month +1

SELECT 
    [columns]
  FROM [table]
and MONTH(Startdate) = @month