如何为不返回任何行的查询设置默认值?

时间:2012-12-27 23:54:25

标签: sql oracle triggers default rows

我用select语句创建了一个触发器,我想说这个select语句是不返回任何行,然后在变量“auxiliar”中放入0。我尝试使用NVL(辅助,0),但它不起作用。我怎么能这样做?

SELECT NVL(salary,0) INTO auxiliar FROM BILL WHERE code=:NEW.code;

[更新]我的触发器代码:

IF preCondicio THEN
        KMpendents:=coalesce(SELECT rev_pendent_km
            INTO KMpendents
            FROM REV_PENDENT
            WHERE rev_pendent_vehicle_codi=:NEW.lloguer_vehicle_codi,0);
        IF KMtotals+KMpendents>=15000 THEN
            SELECT venedor_codi 
            INTO venedorCodi 
            FROM venedor 
            WHERE venedor_alta=(
                SELECT MAX(venedor_alta) 
                FROM venedor 
                WHERE venedor_delegacio_codi=(
                    SELECT venedor_delegacio_codi
                    FROM venedor
                    WHERE venedor_codi=:NEW.lloguer_venedor_codi));
            INSERT INTO REVISIONS VALUES(:NEW.lloguer_vehicle_codi,:NEW.lloguer_dataf,KMtotals+KMpendents,venedorCodi);
            IF KMpendents!=0 THEN
                DELETE FROM REV_PENDENT 
                WHERE rev_pendent_vehicle_codi=:NEW.lloguer_vehicle_codi;
            END IF;
        ELSE
            IF KMpendents!=0 THEN
                UPDATE REV_PENDENT SET rev_pendent_km=KMtotals+KMpendents WHERE rev_pendent_vehicle_codi=:NEW.lloguer_vehicle_codi;
            ELSE INSERT INTO REV_PENDENT VALUES(:NEW.lloguer_vehicle_codi,KMtotals,:NEW.lloguer_dataf);
            END IF;
        END IF;
    END IF;

变量 KMpendents 等同于我在更新之前告知的变量 auxiliar 。但Oracle向我展示了这些错误:

  

PLS-00103:遇到其中一个符号时遇到符号“,”   以下:。 (* @%& - +; / at表示mod余数rem和or group   有交叉减号开始联合连接||指示符   多重集

2 个答案:

答案 0 :(得分:0)

BEGIN
 SELECT NVL(salary,0) INTO auxiliar FROM BILL WHERE code=:NEW.code;
EXCEPTION
  WHEN NOTFOUND THEN
      auxiliar := 0;
END;

或者您也可以使用SQL%NOTFOUND来检查语句是否返回no rows

CREATE or REPLACE TRIGGER trigger_name
BEFORE INSERT
   ON table_name
   [ FOR EACH ROW ]

DECLARE
   -- variable declarations

BEGIN
    ....
    ....
    BEGIN
     SELECT NVL(salary,0) INTO auxiliar FROM BILL WHERE code=:NEW.code;
    EXCEPTION
      WHEN NOTFOUND THEN
          auxiliar := 0;
    END;
    --Yes, this is possible and valid.

EXCEPTION
   WHEN ...
   -- exception handling

END;

答案 1 :(得分:0)

如果select子句只包含聚合函数,那么总会返回至少一行。

SELECT coalesce(sum(salary),0)
INTO   auxiliar
FROM   BILL
WHERE  code=:NEW.code;