Oracle subroutine parameter mode IN OUT NOCOPY

  • 2020-10-31 22:01:29
  • OfStack

IN is used to pass in parameters, which can be variables, constants, or expressions, and cannot be changed within a subroutine.

 
DECLARE 
n NUMBER := 10; 
PROCEDURE do_something ( 
n1 IN NUMBER) IS 
BEGIN 
dbms_output.put_line(n1); -- prints 10 
--n1:=20; --illegal assignment. 
END; 
BEGIN 
do_something(n); 
do_something(20); 
END; 

The OUT pattern is used to return a value that must be passed in as a variable call. The initial value of a variable is not passed in as a formal parameter, for example < < 1 > > Shown below.
The value of the formal parameter is copy to the argument only when the subroutine returns (not when the formal parameter changes), such as < < 2 > > If an exception occurs before return, the value of the actual parameter is not changed.
 
DECLARE 
n NUMBER := 10; 
PROCEDURE do_something ( 
n1 OUT NUMBER) IS 
BEGIN 
dbms_output.put_line('before assign: ' || n1); -- prints none <<1>> 
n1:=20; 
dbms_output.put_line('before return: ' || n); -- prints 10 <<2>> 
END; 
BEGIN 
do_something(n); 
dbms_output.put_line('after return: ' || n); -- prints 20 
END; 

The NOCOPY pattern is used to qualify whether the OUT pattern is called by reference (it's just a compiler hint that it always works), and by default, the arguments to the OUT pattern are called by value.
IN is mainly used for passing in parameters. Although n2 := 20 is called, it does not take effect until the return. Such as < < 1 > > Shown below.
NOCOPY is a pass reference that takes effect immediately upon assignment, for example < < 2 > > If an exception occurs before the return, the value of the actual parameter is also changed.
Since the OUT parameter converts the value copy to the actual parameter when the subroutine returns, the value of n after the call is 20, for example < < 3 > > Shown below.
 
DECLARE 
n NUMBER := 10; 
PROCEDURE do_something ( 
n1 IN NUMBER, 
n2 IN OUT NUMBER, 
n3 IN OUT NOCOPY NUMBER) IS 
BEGIN 
n2 := 20; 
dbms_output.put_line(n1); -- prints 10<<1>> 
n3 := 30; 
dbms_output.put_line(n1); -- prints 30 <<2>> 
END; 
BEGIN 
do_something(n, n, n); 
dbms_output.put_line(n); -- prints 20 <<3>> 
END; 


Related articles: