我的查询有问题吗? (DATEDIFF)

时间:2012-06-26 11:49:26

标签: sql

此查询应该用于获取在特定日期创建的学生数据。但是,如果我为@NumberOfDays输入15,它将返回15天和14天的数据,如果我输入20,这次它会带来19天和20天的数据。有人可以帮我解决我的疑问吗?我不知道我做错了什么。

SELECT TOP 10 S.Id, S.Name, S.Surname, S.DateCreated
FROM STUDENT S WITH(NOLOCK)
WHERE DATEDIFF(day, CAST(S.DateCreated AS date), CAST(GETDATE() AS date)) = @NumberOfDays

2 个答案:

答案 0 :(得分:0)

SELECT TOP 10 S.Id, S.Name, S.Surname, S.DateCreated
FROM STUDENT S WITH(NOLOCK)
WHERE DATEDIFF(day, CAST(S.DateCreated AS date), CAST(GETDATE() AS date)) 
Between @NumberOfDays-1 and @NumberOfDays

答案 1 :(得分:0)

通过此查询,它最终有效!

SELECT TOP 10 S.Id, S.Name, S.Surname, S.DateCreated
FROM STUDENT S WITH(NOLOCK)
WHERE CAST(S.DateCreated AS DATE) = CAST(DATEADD(DAY, -@NumberOfDays, GETDATE()) AS DATE)