0

I am using SWITCH Statement in SP under Where Clause.Query Seems to be fine but i am unable to understand why it is giving me the error. Query is:

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    
(C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
AND 
 CASE @abc
         WHEN 2 THEN I.RecurringCharge=@Total or @Total is NULL
         WHEN 3 THEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL 
     END

The code is incomplete but sufficient to understand the problem.I am getting Below Error Message when trying to compile it.

Incorrect syntax near '='.

The Error is on following line.

WHEN 2 THEN I.RecurringCharge=@Total or @Total is NULL

Please help me experts.

Thanks in advance.

5
  • 1
    The T-SQL CASE statement can only return (atomic) values (like 1, Hello) - not entire code blocks or expressions... Commented Nov 1, 2012 at 7:43
  • but this is my requirment to return like above based on @abc. Can i fix it somehow ,or there is no solution for it ? Commented Nov 1, 2012 at 7:49
  • I don't understand what you're trying to do - in the middle of your WHERE clause, you're trying to assign variables and stuff..... Commented Nov 1, 2012 at 8:18
  • possible duplicate of How to use If Statement in Where Clause in SQL? Commented Nov 1, 2012 at 11:32
  • @Asp_Newbie I would suggest going back to your unresolved problem and UNMARKING it as accepted. It is going to mislead visitors to the page. Also look at my answer on that question for rephrasing your query. Actually, you should list some rows of data and the expected results to be absolutely clear what logic you are after. Commented Nov 1, 2012 at 11:33

1 Answer 1

2

See the documentation of the CASE sattement.

Instead CASE <variable> WHEN <value> ... you should use CASE WHEN <variable>=<value> ....

In your case, you'd be better off not useng CASE at all. Try rewriting the conditions like this instead

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
AND    (@Total is NULL OR
            (
                (@abc = 2 and I.RecurringCharge=@Total)
                OR
                (@abc = 3 and I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%')
            )
        )

I indented the conditions just to make it clear how they are applied. I also factored out the common OR @Total is NULL condition.

Sign up to request clarification or add additional context in comments.

Comments

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.