开发者

TSQL Case in where statement if parameter is null

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:

 s开发者_如何学Pythonelect * from table
  where MadeByUserId = @madeByUserId (if(@reportedByUserID != null) and ReportedByUserID = @reportedByUserID)

Basically I want to make a case in the where clause to include another filter condition based of the null/not null state of the @reportedByUserId

Is that possible?

Thanks a lot, Radu


Try:

 select * from table
 where MadeByUserId = @madeByUserId 
 AND (@reportedByUserID IS null OR ReportedByUserID = @reportedByUserID)


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.


Add an if statement

IF (@reportedByUserId IS NOT NULL)

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜