TSQL Case in where statement if parameter is null

前端 未结 4 1231
失恋的感觉
失恋的感觉 2021-02-06 01:09

I have a SP that gives me a lot of hard times.

The sp gets a two parameters @madeByUserId and @reportedByUserId. I want to have something like:

 select          


        
相关标签:
4条回答
  • 2021-02-06 01:38

    You could use COALESCE.

    SELECT  * 
    FROM    Table
    WHERE   MadeByUserId = @madeByUserId 
            AND ReportedByUserID = COALESCE(@reportedByUserID, ReportedByUserID)
    

    This translates to

     if @reportedByUserID is `NOT NULL` then 
       compare ReportedByUserID with @reportedByUserID
     else
       compare ReportedByUserID with ReportedByUserID
    

    From MSDN

    COALESCE

    Returns the first nonnull expression among its arguments.

    0 讨论(0)
  • 2021-02-06 01:45

    I think this will give you what you're after.

    IF (@reportedByUser IS NULL)
        select * from table 
        where MadeByUserId = @madeByUserId
    ELSE
        select * from table 
        where MadeByUserId = @madeByUserId and ReportedByUserID = @reportedByUserID)
    
    0 讨论(0)
  • 2021-02-06 01:47

    Try:

     select * from table
     where MadeByUserId = @madeByUserId 
     AND (@reportedByUserID IS null OR ReportedByUserID = @reportedByUserID)
    
    0 讨论(0)
  • 2021-02-06 02:01

    Add an if statement

    IF (@reportedByUserId IS NOT NULL)

    SELECT * FROM table t WHERE t.MadeByUserId = madeByUserId etc

    0 讨论(0)
提交回复
热议问题