0

I have a query in SQL Server with the following where condition

where  (Convert(date,AppDate) between Convert(date,''+@DateFrom +'') AND
    Convert(date,''+@DateTo+'') and DrCode =  '' +@DrCode+'' ) 

But I want to add and DrCode = '' +@DrCode+'' when DrCode>0

How to set it?

aparna rai
  • 823
  • 10
  • 24
  • 1
    Possible duplicate of [How do write IF ELSE statement in a MySQL query](https://stackoverflow.com/questions/8763310/how-do-write-if-else-statement-in-a-mysql-query) – Sainath Krishnan Sep 11 '18 at 08:31

2 Answers2

2

I don't know why you are doing string concatenations like this:

'' + @DateFrom + ''

In any case, I don't think a CASE expression is appropriate for what you want to do. Just spell out the logic directly in the WHERE clause:

WHERE
    CONVERT(date, AppDate) BETWEEN
        CONVERT(date, @DateFrom) AND CONVERT(date, @DateTo) AND
        ((DrCode = @DrCode AND DrCode > 0) OR DrCode <= 0);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

If you want to use DrCode > 0 condition with DrCode = '' +@DrCode+'' separately then you can try the following:

where (Convert(date,AppDate) between Convert(date,''+@DateFrom +'') AND
    Convert(date,''+@DateTo+'')) and 
    (CASE WHEN DrCode > 0 AND DrCode =  '' +@DrCode+'' THEN 1 ELSE 0 END =1)
akshay
  • 777
  • 4
  • 15