0

How can I return IS NOT NULL on from a SQL Server CASE statement?

I have tried something like this:

WHERE 
    a.BillToCustomerID IS NOT NULL
    AND CASE @taxSchedRequiered
           WHEN 1 THEN a.TaxScheduleID IS NOT NULL
        END

but it is not working for me.

Update

I need to filter by a.TaxScheduleID IS NOT NULL, just in the specific case when the value of the variable @taxSchedRequiered (possible values are: null, 0, 1) is 1.

5
  • Your question is not very clear. Perhaps this can point you in the right direction anyway: where 'TRUE' = case when @taxSchedRequired = 1 and a.TaxScheduleID is not null then 'TRUE' else 'FALSE' end and a.BillToCustomerID is not null Commented Nov 13, 2019 at 18:50
  • What do you want to do? Commented Nov 13, 2019 at 18:50
  • 1
    CASE in T-SQL is an expression (like a+b - not a statement) that can return one, atomic value (from several possible values) - but you cannot use CASE to conditionally/optionally add/run code snippets like you're trying to do..... Commented Nov 13, 2019 at 18:51
  • Just search "case in where clause" Commented Nov 13, 2019 at 19:04
  • @avery_larry you are right, I edit the question, trying to be more clear. Commented Nov 13, 2019 at 19:07

1 Answer 1

1

just change the logic and use an OR

WHERE 
    a.BillToCustomerID IS NOT NULL
    AND (@taxSchedRequiered <> 1 OR a.TaxScheduleID IS NOT NULL)

this will include all records if @taxSchedRequiered = 0 else it will only include records that have a a.TaxScheduleID <> NULL

Also make sure that @taxSchedRequired has a value other than NULL when you execute this

Edit to check for null param

WHERE 
    a.BillToCustomerID IS NOT NULL
    AND (ISNULL(@taxSchedRequiered,0) = 0 OR a.TaxScheduleID IS NOT NULL)
Sign up to request clarification or add additional context in comments.

2 Comments

the variable taxSchedRequiered will just tell me if I have to filter by a.TaxScheduleID IS NOT NULL, or not.
@jczmog above should do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.