触发和计数(*)不起作用

时间:2012-11-23 09:11:21

标签: oracle plsql

我写了触发器来检查客户是否有任何暂停帐户。如果是,他将无法创建新帐户,但是当我尝试插入时,插入仍然会通过。有人可以帮我这个吗?

CREATE OR REPLACE TRIGGER SuspendedAccount
BEFORE INSERT ON ACCOUNT

FOR EACH ROW

DECLARE

varIsProblemAccount Int;

BEGIN

SELECT COUNT(*) INTO varIsProblemAccount
FROM ACCOUNT
WHERE CUSTID = :new.custID
    AND ACCSTATUS = 'Suspended';

IF (varIsProblemAccount >= 1) THEN      
        DBMS_OUTPUT.PUT_LINE('*************************************************');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Transaction canceled. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Refer customer to the manager immediately. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('**************************************************');
        RETURN;
    END;

ELSIF (varIsProblemAccount = 0) THEN

    BEGIN
        DBMS_OUTPUT.PUT_LINE('*************************************************');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Transaction completed. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Thank the customer for their business. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('**************************************************');
    END;
END IF;
END;

抱歉,我试图更改为0,因为它永远不会是“NULL”但它仍然无法正常工作

3 个答案:

答案 0 :(得分:2)

问题是你的其他条件!

CREATE OR REPLACE TRIGGER SuspendedAccount
BEFORE INSERT ON ACCOUNT

FOR EACH ROW

DECLARE

varIsProblemAccount Int;

BEGIN

SELECT COUNT(*) INTO varIsProblemAccount
FROM ACCOUNT
WHERE CUSTID = :new.custID
    AND ACCSTATUS = 'Suspended';

IF (varIsProblemAccount >= 1) THEN      
        DBMS_OUTPUT.PUT_LINE('*************************************************');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Transaction canceled. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Refer customer to the manager immediately. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('**************************************************');
        RETURN;
    END;

-- count() never returns NULL
ELSIF (varIsProblemAccount = 0) THEN

    BEGIN
        DBMS_OUTPUT.PUT_LINE('*************************************************');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Transaction completed. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('   Thank the customer for their business. ');
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('**************************************************');
    END;
END IF;
END;

答案 1 :(得分:1)

尝试更改以下代码

ELSIF (varIsProblemAccount = null) THEN

ELSIF (varIsProblemAccount = 0) THEN

答案 2 :(得分:1)

您的触发器无法阻止INSERT - RETURN过早退出触发器主体。

如果要阻止INSERT,则应该引发异常:

IF (varIsProblemAccount >= 1) THEN      
    raise_application_error(-20001, 'Existing account found');
END;