简体   繁体   中英

When @parm =-1 return with IN, else return @parm value

I would like to filter my query but do know the syntax:

Here is my incorrect syntax:

WHERE 
 (@StatusId = - 1 then Status.StatusId IN (1, 2, 3, 4)) 
else 
  Status.StatusId = @StatusId)
WHERE
(@StatusId = -1 AND Status.StatusID IN (1,2,3,4))
OR
(@StatusId <> -1 AND Status.StatusID = @StatusId)

Note that @StatusId <> -1 returns false if @StatusId is null. I'm assuming that the equality check should only happen if @StatusId does not equal -1. If that's not the case, then you can remove that part from the second clause.

You need to use Boolean logic. Try this:

WHERE 
 ((@StatusId = - 1 AND Status.StatusId IN (1, 2, 3, 4)) OR Status.StatusId = @StatusId)

Note that the whole statement is in parenthesis.

You could do it like this, but it can cause query performance problems doing it this way (search for parameter sniffing). Better would be to generate the correct SQL dynamically depending on the value of @StatusID and only run the bit you need.

Where (
  @StatusID = -1 And 
  Status.StatusID In (1, 2, 3, 4)
) Or (
  @StatusID != -1 And
  Status.StatusID = @StatusID
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM