-- Create table
create table USER_INFO
(
ID
VARCHAR2(4),
NAME
VARCHAR2(15),
PWD
VARCHAR2(15),
ADDRESS VARCHAR2(30),
AGE
NUMBER
)
tablespace SYSTEM
pctfree 10
pctused 40
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
1.创建存储过程更新user_info.name
create or replace procedure update_name (v_name varchar2,v_id varchar2) as
begin
update user_info set name = v_name where id = v_id;
commit;
end update_name;
调用存储过程
declare
v_name varchar2(6):= 'qi';
//变量类型可以写 user_info.name%TYPE,但是不能写 varchar2
v_id varchar2(6) := 'u001';
begin
update_name(v_name,v_id);
end;
commit
2.创建function
create or replace function getAge(v_id varchar2)
return number as v_age number;
begin
select age into v_age from user_info where id = v_id;
return v_age;
end getAge;
使用 function
select getAge('u001') from dual
3.带 out 参数的 procedure
create or replace procedure get_age(v_id in varchar2, v_out out number)
as v_age number;
begin
select age into v_age from user_info where id = v_id;
if v_age < 10 then
v_out:=0;
else
v_out:=1;
end if;
commit;
end get_age;
declare
v_out number;
begin
get_age('u001',v_out);
dbms_output.put_line(v_out);
end;
4.使用游标
create or replace procedure testCursor as
Cursor mycursor is select name from user_info;
v_name user_info.name%TYPE;
begin
for
v_name
in
mycursor
LOOP
dbms_output.put_line(
v_name.name
);
end
LOOP
;
end
testCursor;
总结:没有参数的时候不用加括号,没有定义局部变量的时候也要有 as
5.while 的使用
create or replace procedure testWhile(num in number) as
i number;
begin
i := num;
while i<10 loop
dbms_output.put_line(i);
i := i + 1; // 不能使用参数 num := num + 1; num 不能用于赋值
end loop;
end testWhile;
declare
v_num number:=1;
begin
testWhile(v_num);
end;
6.if 条件语句
create or replace procedure test_if(v_num in number) as
begin
if v_num=1 then
dbms_output.put_line(v_num);
elsif v_num=2 then // 不是else if
dbms_output.put_line(v_num);
end if;
end test_if;
declare
v_num number:=2;
begin
test_if(v_num);
end;