使用“OR”执行 SQL SERVER 表达式的所有部分得到评价?
给定:
WHERE (@Id Is NULL OR @Id = Table.Id)
如果 @Id 为 null:表达式的计算结果为 true。第二部分 @Id = Table.Id 是否仍然被考虑?或者,如果第一部分是(c# 中的情况),则表达式计算结果为 true 就足够了。
这是相关的,因为有一些更复杂的 OR 语句,其中了解是否所有部分都得到评估非常重要。
更新:
我发现这种语法是一个很好的选择
WHERE (Table.Id = ISNULL(@Id, Table.Id))
Given:
WHERE (@Id Is NULL OR @Id = Table.Id)
If @Id is null: the expression evaluates to true. Does the second part @Id = Table.Id still get considered? or is it sufficient that the expression evaluates to true given that the first part is (which is the case in c#).
This is relevant because of some much more complex OR statements where it is important to know if all parts are getting evaluated.
UPDATE:
I have since found this syntax to be a good alternative
WHERE (Table.Id = ISNULL(@Id, Table.Id))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有时是,有时不是。 SQL Server 不保证布尔运算符短路,不要依赖它来保证正确性。请参阅此博客条目:布尔运算符短路< /a>.
像这样依赖于 @variables 的复杂查询最好写成显式 IF 语句:
Sometimes they are, sometimes they aren't. SQL Server does not guarantee boolean operator short circuit, don't rely on it for correctness. See this blog entry: Boolean Operator Short Circuit.
Complex queries that depend on @variables like this are much better written as explicit IF statements:
对于这样的查询,执行计划可能不太好。
两者都将受到评估。
Execution plans may not be so great with a query like that.
Both will be evaluated.