存储过程以输出参数返回布尔值的该写法是否合法有效?
Is This a Valid Way to Return a Boolean via Output Parameter in an Oracle Procedure?
Absolutely, this is a valid approach to use an output parameter to return a success boolean status, while throwing exceptions to signal execution failures. Let’s break down why this works and some key points to keep in mind:
How This Implementation Meets Your Requirements
Your procedure follows the intended logic perfectly:
- Success case: When both
INSERTstatements run without errors and theCOMMITcompletes, theRESULToutput parameter is explicitly set toTRUE. This guarantees the caller only gets aTRUEvalue when all operations fully succeed. - Error case: If any exception pops up during execution, the procedure triggers the
EXCEPTIONblock:- It rolls back all uncommitted changes with
ROLLBACKto keep data consistent. - After running your custom error handling (
//Do stuff;), it re-raises the exception withRAISE, passing the error up to the caller. This means the caller will never get a misleadingRESULTvalue (like an uninitializedNULL) when something goes wrong.
- It rolls back all uncommitted changes with
Best Practices & Small Improvements
While the core logic is solid, here are a few tweaks to make it more robust:
- Avoid over-reliance on
WHEN OTHERS: Catching every exception withWHEN OTHERScan hide unexpected issues. Whenever possible, add specific handlers for known error types (e.g.,DUP_VAL_ON_INDEXfor unique constraint violations) before theWHEN OTHERSblock. This lets you handle different errors appropriately while still catching unforeseen issues as a fallback. - Initialize the output parameter (optional): You could set
RESULT := FALSEat the start of the procedure. This makes it clearer that aFALSEvalue (instead ofNULL) would indicate an incomplete execution—though since you re-raise exceptions, the caller will likely never encounter this uninitialized state. - Make sure the caller handles exceptions: Any code invoking this procedure needs an
EXCEPTIONblock to catch the raised errors. Otherwise, the exception will bubble up to the application layer and might cause unhandled crashes.
Your Formatted Procedure Code
PROCEDURE STUFF (VAL1 IN NUMBER, VAL2 IN NUMBER, RESULT OUT BOOLEAN) IS BEGIN INSERT INTO TABLE_1 (A_COLUMN) VALUES (VAL1); INSERT INTO TABLE_2 (B_COLUMN) VALUES (VAL2); COMMIT; RESULT := TRUE; EXCEPTION WHEN OTHERS THEN ROLLBACK; -- Do stuff; (replace comment with actual error handling logic) RAISE; END;
内容的提问来源于stack exchange,提问作者Popplar
相关产品推荐
相关产品推荐

