sqlsql-serverdatabasestored-procedures

SQL condition based on variable value


I have to perform a query and it's where the condition should depend on the variable value.

For example, if variable @EventId = 0, then the condition should be:

select * 
from tbl_event 
where event_id != @EventId

And if variable @EventId = 10, then the condition should be:

select * 
from tbl_event 
where event_id = @EventId

I have to do this in a SQL Server stored procedure.

Can anyone help me out?


Solution

  • Condition 1: Match @EventId = 0 and event_id != @EventId

    Condition 2: Match @EventId = 10 and event_id = @EventId

    To fulfill either of these conditions, you need OR operator.

    SELECT * 
    FROM tbl_event 
    WHERE (@EventId = 0 AND event_id != @EventId)
      OR (@EventId = 10 AND event_id = @EventId)