-1

If variable1 is null Select *from table Where condition1 And condition 2 And a is not null and b is not null Else Select * from table Where condition 1 And conditon 2 And a is null and b is null

How to write this as a dynamic SQL query since only the last 2 conditions change in 'if and else'?

1 Answers1

0

This may or may not work, depending on which DB is being used.. Give it a try.

Select * from ConditionalWhere
Where condition1 = 1
  And condition2 = 1
  AND  CASE When (variable1 is null) 
              And ([a] is not null) 
              and ([b] is not null) 
              Then 1
            When (variable1 is not null)                        
              and ([a] is null)     
              and ([b] is null)     
              Then 1 
            Else 0
       End = 1
donPablo
  • 1,937
  • 1
  • 13
  • 18
  • If variable1 is not null Select X from table into y Where a=b And c=d And e is not NULL and f is not NULL Else Select x from table into y Where a=b And c=d And e is NULL and f is NULL Slightly modified my question. In the above case how to write a single dynamic query? – Maha Lakshmi Mar 18 '19 at 05:27
  • @MahaLakshmi Please use the above pattern to construct your own next SQL – donPablo Mar 19 '19 at 00:55