SQL where 短路小用

说起园子,我已经来了很久,但是写点个人的心得还是头一次,感觉上还是很紧张的!

最近有写一些sql句子,总是碰到像是在 where 条件之后需要加一些判断的情况:

举些列子来说明我碰到的情况:

1.根据传递的参数来拉退票的订单:

declare @isRtn int
set @isRtn=1 

select * from SalesOrderLine

where InputDateTime>='2013-5-1' and state=2

and((@isRtn=1 and OriginalSOLID is not null) or(@isRtn=0 and OrigianlSOLID is null))

说明:

OriginalSOLID 表示如果是退单则记录原始订单号

@isRtn=0 表示查询状态为2的订单,@isRtn=1 表示查询状态为2的退单

 

2.根据时间参数@startTime是否为空来加where的选择条件,也就是如果时间不为空,则InputDateTime>@startTime,

如果@startTime为空,那么就不加这样的条件

declare @startTime dateTime,@endTime dateTime

select * from SalesOrderLine 

where (@startTime is null or InputDateTime>=@startTime)

and (@endTime is null or InputDateTime<@endTime)

 

应用短路原理可以实现在where 条件后面的不好写判断的目的。如果应用的好的话,会事半功倍!

 

posted @ 2013-11-20 13:52  00jiajia  阅读(993)  评论(0编辑  收藏  举报