Oracle:sql select查询,如果条件参数为空,则忽略该参数

ani*_*rma 5 java sql oracle

假设我有一个 oracle 查询

SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = ?
    AND DESIGNATION = ?
    AND DISTRICT = ?
    AND CIRCLE = ?
Run Code Online (Sandbox Code Playgroud)

并且很可能参数 (?) 的任何 1 或 2 或 3 可以为空或 null。
那么我该怎么做才能让where子句中的空参数完全“忽略”,只搜索表中的非空参数。
我怎样才能做到这一点

请帮忙.. 查询必须兼容oracle 10g。谢谢

Pon*_*ons 10

您可以重写查询,如:

select * 
  from EMPLOYEE 
  where (DEPARTMENT  = p1 or p1 is null)  
    and (DESIGNATION = p2 or p2 is null) 
    and (DISTRICT    = p3 or p3 is null)
    and (CIRCLE      = p4 or p4 is null)
Run Code Online (Sandbox Code Playgroud)

或者:

select * 
  from EMPLOYEE 
  where DEPARTMENT  = nvl(p1, department)
    and DESIGNATION = nvl(p2, designation)
    and DISTRICT    = nvl(p3, district)
    and CIRCLE      = nvl(p4, circle)
Run Code Online (Sandbox Code Playgroud)

正如@mathguy 在评论中提到的,第二个版本不会显示空值。请使用第一个版本。

  • 如果基表中的 CIRCLE(比如说)为 NULL,第二个版本会做什么?这是想要的行为吗?正确答案是您提出的第一个版本。 (2认同)