Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

sql - How to remove condition check in the where clause statement?

I would like to know how to use if/else or case statement in the below query or anything that could achieve the purpose. The idea is that, whenever a keyword is NULL or blank, I don't want to include the pv.AdminPost = 1 and pv.IsStaff = 1 condition in the Where statement.

Is there any way to do it ? Thank you.

    ;WITH cte 
            AS (SELECT fv.Id, fv.[Description] 
                FROM FeedView fv
                WHERE  (fv.Id =  @PostId OR fv.[Description] LIKE '%' + @Keyword + '%' OR @Keyword IS NULL ) AND fv.ForUserId = @UserId
                UNION 
                SELECT pv.Id, pv.[Description]  
                FROM PublicView pv
                WHERE @InculdePublicPosts = 1 -- This acts as an off switch to decide whether to include public post or not.    
                      OR pv.AdminPost = 1 OR pv.IsStaff = 1 -- how to remove this condition when Keyword is NULL or empty
                      AND (pv.Id =  @PostId OR pv.[Description] LIKE '%' + @Keyword + '%' OR @keyword IS NULL )
            )

SELECT cte.Id, cte.[Description]
FROM .....
question from:https://stackoverflow.com/questions/66056072/how-to-remove-condition-check-in-the-where-clause-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must use proper paranthesis and OR condition as follows:

WHERE @InculdePublicPosts = 1 
  AND ((@keyword IS NULL OR @keyword = '')  OR pv.AdminPost = 1 OR pv.IsStaff = 1)
  AND (pv.Id =  @PostId OR pv.[Description] LIKE '%' + @Keyword + '%' OR @keyword IS NULL )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...