Conditional Operator in SQL Where Clause

前端 未结 5 2046
我寻月下人不归
我寻月下人不归 2020-12-20 16:47

I\'m wishing I could do something like the following in SQl Server 2005 (which I know isnt valid) for my where clause. Sometimes @teamID (passed into a stored procedure) wi

5条回答
  •  萌比男神i
    2020-12-20 17:23

    Even simpler than Andomar's answer, and assuming that id is never 0 (as for most auto-increment ids) is

    SELECT  Team.teamID 
    FROM    Team
    WHERE   @teamid = 0 or Team.teamID = @teamid;
    

    That predicate is always true when @teamid is zero, and otherwise only true when it matches a particular row's teamId.

    Note however: this works pretty efficiently on Sybase 11 or above; it worked pretty inefficiently on MS SQL server 2003; I don't know how it works on the current version of MS SQL Server.

    Also, you can use case; you just have to put the case in where clause, not the where clause in the case. So your original query would be:

    Select Team.teamID 
    From Team
    where 
       case when @teamid = 0 then 0 else Team.teamID end = @teamId;
    

    Note that this is likely to be less efficient, however, as it must be evaluated per row and will also likely result in a full table scan.

    The form I gave above is more likely to be rewritten by a smart query optimizer (your mileage depends on your RDBMS) to use an index when @teamid is not zero.

提交回复
热议问题