如何在value为NULL时引发异常

时间:2018-03-21 17:50:22

标签: plsql

当我比较loadid时,如果nullloadid = V_LOAD_ID,我该如何引发例外?

E_NULL_ID是我当时想要使用的例外。

这是我的程序:

CREATE OR REPLACE PROCEDURE GET_INFO(P_CURDATE DATE)
AS
    V_LOAD_ID CARSALES.LOADID%TYPE;
    E_NULL_ID EXCEPTION;
BEGIN
    -- Get load id from LoadIds table for current date.
    SELECT LoadId
    INTO V_LOAD_ID
    FROM LoadIds
    WHERE DateLoad = P_CURDATE;
    -- Select brand name and total sales.
    SELECT BrandName,  SUM(Cost) 
    FROM CarSales Sales INNER JOIN 
        CarLables Lables ON Lables.CarBrandId = Sales.CarBrandId
    WHERE LoadId = V_LOAD_ID
    GROUP BY CarBrandId
EXCEPTION
    WHEN E_NULL_ID THEN
        DMBS.OUTPUT.PUT_LINE('No loadId found');
END;

2 个答案:

答案 0 :(得分:0)

天哪,有很多方法可以做到这一点 这是一种方法,使用raise_application_error,也许你不想这样做 它肯定会抛出异常,但也许你想在错误时做点什么

你可能想通过将它包装在begin-exception-end块中来检查你的select中是否没有行(或太多行)?

CREATE OR REPLACE PROCEDURE GET_INFO(P_CURDATE DATE)
AS
    V_LOAD_ID CARSALES.LOADID%TYPE;
    E_NULL_ID EXCEPTION;
BEGIN
    -- Get load id from LoadIds table for current date.
    SELECT LoadId
    INTO V_LOAD_ID
    FROM LoadIds
    WHERE DateLoad = P_CURDATE;

    IF (V_LOAD_ID IS NULL) THEN
       RAISE_APPLICATION_ERROR(-20001,'V_LOAD_ID is null');
    END IF;

    -- Select brand name and total sales.

        SELECT BrandName,  SUM(Cost) 
-- you need an into here?

        FROM CarSales Sales INNER JOIN 
            CarLables Lables ON Lables.CarBrandId = Sales.CarBrandId
    WHERE LoadId = V_LOAD_ID
    GROUP BY CarBrandId;

--EXCEPTION
--    WHEN E_NULL_ID THEN
--        DMBS.OUTPUT.PUT_LINE('No loadId found');
END;

答案 1 :(得分:0)

首先,你的select语句缺少into子句,它应该是:

SELECT BrandName,  SUM(Cost)
into l_brand, l_sum
FROM CarSales Sales INNER JOIN 
    CarLables Lables ON Lables.CarBrandId = Sales.CarBrandId
WHERE LoadId = V_LOAD_ID;

其次,与Oracle中null的比较总是评估为FALSE,因此检测某些LoadId为空的唯一方法是明确检查null

declare
   ...
   l_nulls number;
begin
   ...
   SELECT count(*) into l_nulls
   FROM CarSales Sales INNER JOIN 
       CarLables Lables ON Lables.CarBrandId = Sales.CarBrandId
   WHERE LoadId IS NULL;
   if l_nulls > 0 then
      raise E_NULL_ID;
   end if;
   ...
end;