Routines - Stored Procedures
We can use the routines to encapsulate what we need action, there are routines stored procedures, functions and triggers.
Here to learn stored procedures -
grammar
create [or replace] procedure $procedure_name$ [(参数列表)]
is/as --相当于declare
begin
[exception]--异常处理
end $procedure_name$;
删除过程:drop procedure $procedure_name$
Create a stored procedure
Create a stored procedure without parameters
create or replace procedure hello
is
begin
dbms_output.put_line('hello world');
end hello;
/ --执行
Create a parameterized stored procedure
There are three modes parameter, the parameter type definition without defining a width
mode | Explanation |
---|---|
in (default) | Model parameters may be transmitted in the form of a variable or a literal value |
out | Model parameters, must be passed as variables, the variables should not be assigned, the results returned by the receiving process |
in out | Model parameters, must be passed as variables |
--输出指定字符串(使用in)
create or replace procedure print(text in varchar2)
is
begin
dbms_output.put_line(text);
end print;
/
--计算结果,返回给调用者(使用out)
create or replace procedure sum(num1 in int,num2 in int,result out int)
is
begin
result := num1 +num2;
end sum;
/
declare
--变量不应该赋值
v_result int := 5;
begin
sum(5,6,v_result);
--上面的语句还可以这样写,这样便于直观的知道参数对应哪一个
--sum(num1 =>5,num2=>6,result=>v_result);
dbms_output.put_line(v_result);
end;
/
--交换两个数字(使用in out)
create or replace procedure swap(a in out int,b in out int)
is
v_temp int ;
begin
v_temp := a;
a := b;
b := v_temp;
end swap;
/
declare
a int :=5;
b int := 9;
begin
swap(a,b);
dbms_output.put_line(a||','||b);
end;
/
carried out
PL / SQL execution
begin
--包名.过程名
--未定义包名,不需要写包名
$procedure_name$;
end;
/
--如果想要其他用户访问当前用户的存储过程,当前用户下,授权给其他用户权限
grant execute on $procedure_name$ to $user_name$;
Command line execution
exec/execute $procedure_name$[(参数)]