减去两个日期

时间:2012-04-16 12:58:37

标签: sql tsql

我想列出在表格中添加特定天数的学生。

@NumberOfDays INT = 15 -- When I list them the added subtraction result must match this result

SELECT S.Name, S.Surname, S.DateAdded
FROM STUDENT S
WHERE (SELECT CAST(GETDATE()-S.DateAdded) = @NumberOfDays)

但这不起作用。有人可以帮我吗?

5 个答案:

答案 0 :(得分:5)

带有增量

DATEADD将扣除;

where S.DateAdded >= dateadd(day, -@NumberOfDays, getdate())

过去15天内添加的任何内容。

答案 1 :(得分:3)

您应该使用DATEDIFF(Transact-SQL)函数,以下应该可以工作:

DECLARE @NumberOfDays INT = 15 -- When I list them the added subtraction result must match this result

SELECT S.Name, S.Surname, S.DateAdded
FROM STUDENT S
WHERE DATEDIFF(day, S.DateAdded, GETDATE()) = @NumberOfDays

有关此功能的更多信息:

http://msdn.microsoft.com/en-us/library/ms189794.aspx

答案 2 :(得分:3)

您需要以这种方式使用DATEADD功能:

declare @numberofdays int
set @numberofdays = 15

SELECT S.Name, S.Surname, S.DateAdded
FROM STUDENT S
WHERE S.DateAdded >= dateadd(day, -@NumberOfDays, getdate())

以下是sqlfiddle

答案 3 :(得分:0)

这个怎么样。

您可以在sql中使用datediff函数来获取日期差异。

DECLARE @numberofdays as int
set @numberofdays = 15

SELECT S.Name, S.Surname, S.DateAdded
from STUDENT S
where datediff(dd,S.DateAdded,getdate())= @numberofdays;

答案 4 :(得分:0)

SELECT S.Name, S.Surname, S.DateAdded 
FROM STUDENT S 
WHERE (SELECT months_between(GETDATE(), S.DateAdded) = @NumberOfDays)