java - 根据某些条件更改 where 子句标准

标签 java sql oracle jdbc

我想要实现的任务: 我有一个查询,其 where 子句条件将根据一个条件动态更新,使其保持在下面的正常编程语言中,这就是我想要实现的目标

考虑到“名称”是我正在检查条件的列

If(name==""){
  select * from infodata where col1='somevalue' and col2='somevalue'
} else if(name=="2"){
  select * from infodata where col3='somevalue' or col4='somevalue'
} else {
  select * from infodata where col2='somevalue' and col5='somevalue'
}

根据该值,我需要分配不同的 where 条件。 (我使用Oracle作为数据库)

目前我通过在Java代码中编写条件来为查询分配相应的where条件来实现这一点

我正在寻找一种在 SQL 查询中执行此操作的方法,以便我可以在准备好的语句中传递所需的数据。只是想知道这是否可以使用单个 SQL 查询来实现,如果可能的话,您能否提供一个示例或语法来实现这一点。

谢谢。

最佳答案

听起来您可以简单地组合条件

select *
  from infodata
 where (name is null and col1 = 'somevalue' and col2 = 'somevalue')
    or (name = '2'   and (col3 = 'somevalue' or  col4 = 'somevalue'))
    or (name != '2'  and col2 = 'somevalue' and col5 = 'somevalue)

请记住,Oracle 没有与 NULL 分开的空字符串的概念,因此我假设您想要检查 name 是否为 NULL在你的第一个条件下。

关于java - 根据某些条件更改 where 子句标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22819832/

相关文章:

java - 导出所有 netbeans 项目和数据库

java - 将方法绑定(bind)到android中的按钮

mysql - 间接连接三个表的多行

sql - 从一列嵌套表中选择 SQL

Java 类扩展了 Groovy 类

java - Groovy Spring @Configuration 使用 @ComponentScan 与多个包

mysql - SQL:在一条语句中进行多个分组

mysql - 检查列的唯一值

oracle - Toad for Oracle..如何执行多条语句?

oracle - 使用 Spring Data Jpa 调用 Oracle 中的存储过程时参数的数量或类型错误