where条件的顺序在sql server中改变结果

时间:2013-12-03 10:25:29

标签: sql sql-server join temp-tables

我在一个查询中遇到了一个独特的问题。

insert into #tempclasssearch
            SELECT cc.Id, B.ScheduleId, 10, Lc.Id LocationId, Lc.GroupId, cc.CategoryId,CCSC.SubCategoryId,cc.RegistrationId
            from Event CC Inner join Batches B
            On Cc.Id = B.ClassCreativeId
            Inner Join Venues V On B.VenueId = V.ID
            Inner Join loc Lc On V.LocId = Lc.id
            Inner join EventSubCategories CCSC on CC.Id = CCSC.EventId
            inner join PackageSubscriptions p on p.userId = cc.userId
            Where 
            p.SubscriptionStatus = 1 and 
            ((@GroupId = 0) or (@GroupId is not null and Lc.GroupId = @GroupId))
            and ((@LocationId = 0) or (@LocationId is not null and Lc.Id = @LocationId))
            and ((@TargetCityId is null) or (@TargetCityId is not null and Lc.TargetCityId = @TargetCityId))                        
            and ((@CategoryId = 0) or (@CategoryId is not null and cc.CategoryId = @CategoryId))
            and ((@SubCategoryId = 0) or (@SubCategoryId is not null and ccsc.SubCategoryId = @SubCategoryId))
            and cc.UserStatus = 1 and cc.PublishStatus = 3 and B.StartDate >= @StartDateTime -- and B.StartDateTime > @StartDateTime
            and ((@EndDateTime is null) or (@EndDateTime is not null and B.StartDate <= @EndDateTime
            and p.StartDateTimeUtc <= GETUTCDATE() 
            and p.EndDateTimeUtc >= GETUTCDATE()

问题在于,如果我将这个条件p.SubscriptionStatus = 1放在最后,那么它就不会执行这个条件,而如果我将它作为第一个条件放置它。

我不知道发生了什么:(

如果你们有任何想法,请告诉我....

1 个答案:

答案 0 :(得分:0)

末尾缺少括号

和((@EndDateTime为null)或(@EndDateTime不为空,B.StartDate&lt; = @EndDateTime