如何为select where子句编写动态SQL查询?

时间:2019-03-18 03:45:31

标签: execute execute-immediate

如果variable1为null       从表中选择*      条件1      条件2  并且a不为null和b不为null 其他      从表中选择*      条件1      和条件2 并且a为null,b为null

由于只有两个条件在'if and else'中发生变化,因此如何将其写为动态SQL查询?

1 个答案:

答案 0 :(得分:0)

根据使用的是哪个数据库,这可能行不通。请尝试一下。

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