使用BETWEEN Statement
无法正确显示特定结果where [Column_name] >= @FromDate and [Column_name] <= @ToDate
以下是我设置值的方法
DECLARE @Today AS datetime
DECLARE @FromDate AS datetime
DECLARE @ToDate AS datetime
SET @Today = GetDate()
SET @FromDate = @Today
SET @ToDate = DATEADD("dd", 7, @Today)
当我将它从7更改为-7时,我发现它无法正常工作,并且显示的是当前查询中未显示的额外结果
你能告诉我哪里出错了吗?
由于
答案 0 :(得分:1)
Aaron Bertrand有一篇广泛的博客,内容是关于为什么你不应该将between
与日期一起使用(见here)。
我猜测你的变量名称是否忘记getdate()
上的 time 组件。因此,请尝试将变量声明为:
DECLARE @Today date;
DECLARE @FromDate date;
DECLARE @ToDate date;
SET @Today = cast(GetDate() as date);
SET @FromDate = @Today;
SET @ToDate = DATEADD(day, 7, @Today);
如果您想避免使用between
,可以将比较逻辑编写为:
where [Column_name] >= @FromDate and [Column_name] < DATEADD(day, 1, @ToDate)
编辑:
在SQL Server 2008之前的版本中,以下内容删除了时间组件:
DECLARE @Today datetime;
DECLARE @FromDate datetime;
DECLARE @ToDate datetime;
SET @Today = DATEADD(day, DATEDIFF(day, 0, getdate()), 0);
SET @FromDate = @Today;
SET @ToDate = DATEADD(day, 7, @Today);