有人可以帮我理解SQL语句的WHERE子句中的每一行是什么意思吗?有两个参数可以为null或有效日期。 where子句如何工作?提前谢谢!
SELECT * from t1
WHERE
((@StartDate IS NULL AND @EndDate IS NULL)
OR (t1.date >= @StartDate AND t1.date <= @EndDate)
OR (t1.date >= @StartDate AND @EndDate IS NULL)
OR (@StartDate IS NULL AND t1.date <= @EndDate))
答案 0 :(得分:3)
如果没有提供范围
,则返回所有条目((@StartDate IS NULL AND @EndDate IS NULL)
或者有一个日期范围,t1.date位于该范围内
OR (t1.date >= @StartDate AND t1.date <= @EndDate)
或日期范围没有结束,t1.date在开始之后
OR (t1.date >= @StartDate AND @EndDate IS NULL)
或者日期范围没有开始,t1.date在范围结束之前
OR (@StartDate IS NULL AND t1.date <= @EndDate))
简单来说,如果没有给出范围,则选择所有条目,或者只选择那些在给定范围内的条目,同时允许开放范围。
至于评论中的示例:
(SomeParameter = 'N' and t1.name IN (Name)) OR
(SomeParameter = 'Y' and t1.name IN (Name) OR t1.name is null)
你的问题是:
如果SomeParameter等于&#39; N&#39;则&#34;和t1.name IN(Name)&#34;将被附加到where子句,否则如果SomeParameter等于&#39; Y&#39;,则&#34;并且t1.name IN(名称)或t1.name为null))&#34;会被附加到where子句。这是对的吗?
没有。 WHERE
子句总是如此。它不是已更改,但已评估。让我们看看它如何适用于这两种情况:
案例1:SomeParameter =&#39; N&#39;
(SomeParameter = 'N' and t1.name IN (Name)) OR
(SomeParameter = 'Y' and t1.name IN (Name) OR t1.name is null)
=>
(TRUE and t1.name IN (Name)) OR
(FALSE and t1.name IN (Name) OR t1.name is null)
如果t1.name in (Name)
也为真,则记录包含在结果集中,因为
(TRUE and TRUE) OR (FALSE AND TRUE OR FALSE) =
TRUE OR (FALSE OR FALSE) =
TRUE OR FALSE =
TRUE
如果t1.name in (Name)
为false,则记录不包含在结果集中,因为
(TRUE and FALSE) OR (FALSE AND FALSE OR FALSE) =
FALSE OR (FALSE OR FALSE) =
FALSE OR FALSE =
FALSE
案例2:SomeParameter =&#39; Y&#39;
(SomeParameter = 'N' and t1.name IN (Name)) OR
(SomeParameter = 'Y' and t1.name IN (Name) OR t1.name is null)
=>
(FALSE and t1.name IN (Name)) OR
(TRUE and t1.name IN (Name) OR t1.name is null)
如果t1.Name in (Name)
也为真,则记录包含在结果集中,因为
(FALSE and TRUE) OR (TRUE AND TRUE OR FALSE) =
FALSE OR (TRUE AND TRUE) =
FALSE OR TRUE =
TRUE
如果t1.Name in (Name)
为false,则记录不包含在结果集中,因为
(FALSE and FALSE) OR (TRUE AND FALSE OR FALSE) =
FALSE OR (TRUE AND FALSE) =
FALSE OR FALSE =
FALSE