--例1
declare
v_name varchar2(10);
begin
select user_name into v_name from tb_rd_user_info where user_name='ywj12';
dbms_output.put_line('name:'||v_name);
exception
when no_data_found then
dbms_output.put_line('error name');
end;
--匿名块
-- 没有名称的pl/sql块,如例1
--命名块
--子程序
-- (1)过程
-- 建立过程时可以指定输入参数(in),输出参数(out)
create or replace procedure update_money(uname varchar2,num number)
is
begin
update tb_rd_user_info set game_money = num
where user_name = uname;
end update_money;
-- 删除
drop procedure update_money;
-- 调用
exec update_money('ywj123',100000);
call update_money('ywj123',100000);
-- 重新编译
alter procedure update_money compile;
-- 授权student用户使用该过程
grant execute on update_money to student;
-- (2)函数
-- 创建
create or replace function get_user_id(uname varchar2)
return number is
uid number;
begin
select user_id into uid from tb_rd_user_info
where user_name=uname;
return uid;
end;
-- 调用
var rs number
call get_user_id('ywj123') into :rs;
-- 删除
drop function get_user_id;
-- 重新编译
alter function get_user_id compile;
-- (3)包
-- 创建(包由包规范和包体两部分组成)
-- 包规范
create package emp_pkg is
procedure update_money (uname varchar2,num number);
function get_user_id(uname varchar2) return number;
end;
-- 包体
create package body emp_pkg is
procedure update_money(uname varchar2,num number)
is
begin
update tb_rd_user_info set game_money = num
where user_name = uname;
end update_money;
function get_user_id(uname varchar2)
return number is
uid number;
begin
select user_id into uid from tb_rd_user_info
where user_name=uname;
return uid;
end;
end;
-- 调用
call emp_pkg.update_money('ywj123',100000);
var rs number
call emp_pkg.get_user_id('ywj123') into :rs;
CREATE OR REPLACE PROCEDURE CHANGE_SALARY(P_EMPNO IN NUMBER DEFAULT 7788,P_RAISE NUMBER DEFAULT 10)
AS
V_ENAME VARCHAR2(10);
V_SAL NUMBER(5);
BEGIN
SELECT ENAME,SAL INTO V_ENAME,V_SAL FROM EMP WHERE EMPNO=P_EMPNO;
UPDATE EMP SET SAL=SAL+P_RAISE WHERE EMPNO=P_EMPNO;
DBMS_OUTPUT.PUT_LINE('雇员'||V_ENAME||'的工资被改为'||TO_CHAR(V_SAL+P_RAISE));
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('发生错误,修改失败!');
ROLLBACK;
END;