【问题标题】:How to write a dynamic SQL query for a select where clause?如何为 select where 子句编写动态 SQL 查询?
【发布时间】:2019-08-08 09:59:13
【问题描述】:

如果变量 1 为空 从表中选择 * 条件1 和条件 2 并且 a 不为空且 b 不为空 别的 从表中选择 * 条件1 和条件 2 a 为空,b 为空

由于“if and else”中只有最后两个条件发生变化,如何将其编写为动态 SQL 查询?

【问题讨论】:

  • 想知道你在处理什么数据库管理器???

标签: execute execute-immediate


【解决方案1】:

这可能有效,也可能无效,具体取决于正在使用的数据库。试一试。

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

【讨论】:

  • If variable1 is not null 从表中选择 X 到 y where a=b And c=d and e is not NULL and f is not NULL Else 从表中选择 x 到 y where a=b And c =d and e is NULL and f is NULL 稍微修改了我的问题。在上述情况下如何编写单个动态查询?
  • @MahaLakshmi 请使用上面的模式来构造你自己的下一个SQL
猜你喜欢
  • 2011-10-30
  • 1970-01-01
  • 2013-11-13
  • 2011-10-16
  • 1970-01-01
  • 2013-06-14
  • 2019-10-04
  • 2013-07-07
  • 2022-01-13
相关资源
最近更新 更多