Even simpler than the Andomar query, and assuming the id is never 0 (as with most auto-increment identifiers),
SELECT Team.teamID FROM Team WHERE @teamid = 0 or Team.teamID = @teamid;
This predicate is always true when @teamid is zero, otherwise it is only true when it matches a specific teamId command.
Please note: this works quite efficiently on Sybase 11 or higher; It worked quite inefficiently on MS SQL Server 2003; I do not know how this works in the current version of MS SQL Server.
Alternatively, you can use case; you just need to put the matter in the where clause, and not in the where clause. So your original request would look like this:
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, since it should be evaluated on each row, and is also likely to lead to a full table scan.
The form above is more likely to be rewritten by the intelligent query optimizer (your mileage depends on your RDBMS) to use the index when @teamid is non-zero.
tpdi
source share