PL / SQL过程 - 如果为null则忽略参数

时间:2014-02-20 08:58:28

标签: sql stored-procedures plsql

我有一个过程,它接受三个参数,然后根据这些参数查询表。现在其中一个可以为null,如果是,我希望在选择的WHERE子句中忽略它。

create or replace PROCEDURE Procedure1 
(
   COUNTRY IN VARCHAR2, MAKE IN VARCHAR2, SERIAL IN number
) AS

BEGIN

DECLARE
  CURSOR c1 IS  select v.ID from vehicle v   
                where v.country = COUNTRY AND 
                      v.make = MAKE AND 
                      ((SERIAL IS NOT NULL AND v.serial = SERIAL) OR 1);


BEGIN 

  FOR e_rec IN c1 LOOP

    DBMS_OUTPUT.PUT_LINE(e_rec.id);

  END LOOP;

END;
END Procedure1;

我试过这样的事情,但它不起作用。

2 个答案:

答案 0 :(得分:2)

您可以使用

之类的条件
WHERE v.country = COUNTRY AND 
                      v.make = MAKE AND 
                     (SERIAL IS NULL or v.serial = SERIAL)

这也可行

WHERE v.country = COUNTRY AND 
                  v.make = MAKE AND 
((SERIAL IS NOT NULL AND v.Serial = SERIAL) OR SERIAL IS NULL)

答案 1 :(得分:1)

试试这个 - 这与@Miller建议只使用NVL功能相同

WHERE v.country = nvl(COUNTRY,v.country) 
AND v.make = nvl(MAKE,v.make)   
AND v.serial = nvl(SERIAL,v.serial)