我正在尝试在我的SQL存储过程的WHERE子句中使用Datediff / DateAdd函数。除了其他主要查询,我的查询包含2个Date列和1个主列: -
WHERE DATE1 BETWEEN @MonthStart AND @MonthEnd
AND "MAINCOLUMN" IS NOT NULL
OR "DATE2" <= DATEADD(MM, -36,GETDATE()) AND "MAINCOLUMN" IS NOT NULL
我想返回MainColumn
Date1
和@MonthStart
之间@MonthEnd
WHERE "DATE1" BETWEEN @MonthStart AND @MonthEnd
AND "MAINCOLUMN" IS NOT NULL
OR "DATE2" BETWEEN DATEDIFF(MM, -36, GETDATE()) AND GETDATE()
AND "MAINCOLUMN" IS NOT NULL
所在的行
或者
MainColumn的Date2栏DATE位于过去36个月之间(从今天到最后3年的日期)
我甚至尝试过:
WHERE "DATE1" BETWEEN @MonthStart AND @MonthEnd
AND "MAINCOLUMN" IS NOT NULL
OR DATEDIFF(MM, DATE2, GETDATE()) <= 36 AND "MAINCOLUMN" IS NOT NULL
和
OR
问题是,一切都在运行,但是它们需要花费很长时间才能运行..在WHERE
条款中添加OR
语句之前,我的报告几乎没有花费4-5分钟来运行其中有200,000行,但在添加{{1}}语句之后,它就会继续运行。
答案 0 :(得分:0)
Parathensis!在这两种情况下,MainColumn
必须为非空。您可以像这样简化WHERE
子句:
WHERE MainColumn IS NOT NULL
AND (DATE1 BETWEEN @MonthStart AND @MonthEnd OR DATE2 <= DATEADD(MM, -36,GETDATE()))
答案 1 :(得分:0)
这可能会帮助你......
CREATE TABLE data
(
id uniqueidentifier primary key,
MainColumn varchar(20),
date1 datetime,
date2 datetime
);
declare @MonthStart int;
Declare @MonthEnd int;
set @MonthStart = 4;
set @MonthEnd = 8;
Select * from data WHERE DATE1 BETWEEN @MonthStart AND @MonthEnd
AND MAINCOLUMN IS NOT NULL
OR DATE2 <= DATEADD(MM, -36,GETDATE()) AND data.MainColumn IS NOT NULL
答案 2 :(得分:-1)
您需要确保正确分组逻辑。尝试:
`WHERE
(
"DATE1" BETWEEN @MonthStart AND @MonthEnd
AND "MAINCOLUMN" IS NOT NULL
) OR (
DATEDIFF(MM, DATE2, GETDATE()) <= 36
AND "MAINCOLUMN" IS NOT NULL
)`
我将OR中任意一侧的部分括在括号中,以确保在任一块为真时触发它。