Oracle:sql select query如果condition参数为null,则忽略参数

时间:2017-08-25 12:38:50

标签: java sql oracle

假设我有一个oracle查询

SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = ?
    AND DESIGNATION = ?
    AND DISTRICT = ?
    AND CIRCLE = ?

很可能参数(?)中的任何1或2或3可以为空或为空 那么我应该怎么做才能使空参数在where子句中完全“忽略”并且只搜索表中的非空参数。
我怎样才能实现这个目标

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

6 个答案:

答案 0 :(得分:2)

您可以重写查询:

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)

或:

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

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

答案 1 :(得分:1)

LNNVL - 描述lnnvl如何评估值。 != - 这是正确的。我在这里没有犯错误。

为什么从column_name = nvl(param,column_name)开始更好。

如果列具有空值并且param具有空值。

null = null => false这行将从结果中排除。

select * from table
where lnnvl(column_name1 != ?) 
  and lnnvl(column_name2 != ?)
  .
  .
  .

答案 2 :(得分:0)

NVL将成为你的朋友。

此函数接受两个输入参数并返回第一个参数,如果第一个参数为NULL,则返回第二个参数。

这样可行:

SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = NVL(yourParam1,DEPARTMENT)
    AND DESIGNATION = NVL(yourParam2,DESIGNATION )
    AND DISTRICT = NVL(yourParam3,DISTRICT )
    AND CIRCLE = NVL(yourParam4,CIRCLE )

答案 3 :(得分:0)

使用decode

SELECT *
FROM EMPLOYEE
WHERE decode(p_DEPARTMENT, NULL, 1, DEPARTMENT, 1, 0) = 1
    AND decode(p_DESIGNATION, NULL, 1, DESIGNATION, 1, 0) = 1
    AND decode(p_DISTRICT, NULL, 1, DISTRICT, 1, 0) = 1
    AND decode(p_CIRCLE, NULL, 1, CIRCLE, 1, 0) = 1

答案 4 :(得分:0)

使用COALESCE:

SELECT *
FROM EMPLOYEE
WHERE COALESCE(DEPARTMENT,0) = COALESCE(:yourParam1,DEPARTMENT,0)
AND COALESCE(DESIGNATION,0) = COALESCE(:yourParam2,DESIGNATION,0)
AND COALESCE(DESIGNATION,0) = COALESCE(:yourParam3,DISTRICT,0)
AND COALESCE(DESIGNATION,0) = COALESCE(:yourParam4,CIRCLE,0)

答案 5 :(得分:0)

使用Coalesce的答案是天才。但是,零需要用单引号引起来。特别是在此示例中,如果参数可能不是数字,则它将抛出SQL,因为实际字段是字符串,而带引号的0是数字。我将此应用到我的代码,它就像一个魅力。建议:

    SELECT *
    FROM EMPLOYEE
    WHERE COALESCE(DEPARTMENT,'0') = COALESCE(:yourParam1,DEPARTMENT,'0')
    AND COALESCE(DESIGNATION,'0') = COALESCE(:yourParam2,DESIGNATION,'0')
    AND COALESCE(DISTRICT,'0') = COALESCE(:yourParam3,DISTRICT,'0')
    AND COALESCE(CIRCLE,'0') = COALESCE(:yourParam4,CIRCLE,'0')

非常感谢您,穆罕默德·奥斯曼·加尼·费萨尔(Mohammad Osman Gani Faisal)!