是否对使用“ OR”的SQL SERVER表达式的所有部分进行求值? [英] Do all parts of a SQL SERVER expression using 'OR' get evaluated?

查看:89
本文介绍了是否对使用“ OR”的SQL SERVER表达式的所有部分进行求值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

 在哪里(@Id为NULL或@Id = Table.Id) 

如果@Id为null:该表达式的值为true。第二部分@Id = Table.Id是否仍然被考虑?



这是很重要的,因为某些复杂得多的OR




更新:



此后,我发现此语法是不错的选择

 在哪里(Table.Id = ISNULL(@Id,Table.Id))


解决方案

有时候是,有时不是。 SQL Server不保证布尔运算符短路,请不要依赖于布尔运算符短路是否正确。请参阅此博客条目:布尔运算符短路



依赖于此类变量的复杂查询最好写为显式IF语句:

  IF(@id IS NULL)
SELECT ... FROM ... WHERE ...
ELSE
SELECT ... FROM ..在哪里...


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))

解决方案

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:

IF (@id IS NULL)
  SELECT ... FROM ... WHERE ...
ELSE
  SELECT ... FROM ... WHERE ...

这篇关于是否对使用“ OR”的SQL SERVER表达式的所有部分进行求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆