欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » Sql随手笔记 » 正文

热门阅读

SqlServer中or和and的优先级分析

创建时间:2012年03月13日 15:01  阅读次数:(18381)
分享到:
原来一直都没有搞清楚sqlserver中and和or的优先级关系,以为他们的优先级都是一样,在执行的时候按出现的顺序从左到右执行。但今天我在写一个约束,如下:
(number >0 and prenumber >0) or (number<0 and prenumber<0)
保存后系统总是自动将我的约束修改如下:
number >0 and prenumber >0 or number<0 and prenumber<0
就是去掉了我的括号,我想,怎么会这样呢?这样不就改变了我的语意了吗?呵呵,查询资料后得知,原来,上面两个约束的意思是一样的。

原因:在SqlServer中,and的优先级比or的优先级要高。所在,在上面的约束中,会先执行or两边的and条件,再执行or条件。

下面,我们可以做一个测试。
创建表及数据如下:
if (object_id('table1') is not null)
begin
drop table table1
end
go

create table table1
(
ID int identity(1,1) primary key,
num1 int not null,
num2 int not null
)

insert into table1(num1,num2) 
select -1,-1
union all
select -1,2
union all
select 1,2
union all
select 0,0

然后我们执行sql
select * from table1 where num1 >0 or num2 >0 and num1<0

如果or与and的优先级是一样的话,那么应该只能查出一条数据,即
ID  num1 num2
2    -1   2

但实际上,我们执行后发现,这有查出两条数据了,
ID  num1 num2
2    -1    2
3    1     2
这是因为它先执行了and的条件,再执行or的条件,即等同如下:
select * from table1 where num1 >0 or (num2 >0 and num1<0)

那么,如果我们一定要sql先执行or条件,就要使用()来改变条件的执行顺序了。还是上面的sql,如果我们要先执行or条件,可以修改sql如下:
select * from table1 where (num1 >0 or num2 >0) and num1<0
来源:.net学习网
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论1条
  • #1楼  评论人:匿名  评论时间:2012-8-29 11:12:27
  • 学习了,原来如此,难怪我的sql老出问题
发表评论:
留言人:
内  容:
请输入问题 63+96=? 的结果(结果是:159)
结  果: