Oracle儲存過程基礎內容
1 基本語法
1.1 無參無變數
create or replace procedure firstPro
as
begin
dbms_output.put_line('hello word, my name is stored procedure');
end;
裡面只有一個輸出語句
呼叫
begin
firstPro();
end;
1.2 無參有變數
create or replace procedure myDemo02
as
name varchar(10);
age int;
begin
name:='xiaoming';
age:=18;
dbms_output.put_line('name='||name||', age='||age);
end;
在as中宣告變數,在begin中賦值,輸出時通過||符號達到連線字串的功能
1.3 有參入門
create or replace procedure myDemo03(name in varchar,age in int)
as
begin
dbms_output.put_line('name='||name||', age='||age);
end;
呼叫時再賦值
begin
myDemo03('xiaoming',18);
end;
1.4 形參實參
create or replace procedure myDemo04(name in varchar,age in int)
as
begin
dbms_output.put_line('name='||name||', age='||age);
end;
呼叫
declare
name varchar(10);
age int;
begin
name:='xiaoming';
age:=18;
myDemo04(name=>name,age=>18);
end;
呼叫的時候如果需要變數,就可以在declare中宣告,然後執行的時候把變數值通過=>從右向左賦值給引數,要用都要用,此時不能myDemo04(name=>name,18)
1.5 in,out引數
create or replace procedure myDemo05(name out varchar,age in int)
as
begin
dbms_output.put_line('age='||age);
select 'xiaoming' into name from 名字表;
end;
in就是呼叫方法時賦值,是來自方法外的值,而out是要自己查詢出的值,在呼叫的時候就已經有了,而已賦值給其他變數
declare
name varchar(10);
age int;
begin
myDemo05(name=>name,age=>10);
dbms_output.put_line('name='||name);
end;
這個name是out,人家在內部查詢出來,呼叫的時候就有值了,然後賦值給接收變數,下面還能輸出,而in只能是呼叫時賦值.
2 增刪改查
2.1 操作
create or replace procedure mydemo07(ids in int, username in varchar,userpass in varchar, userage in int)
as
begin
-- insert into students(id,username,userpass,userage) values(ids,username,userpass,userage);--增
-- delete from students where id=ids;--刪
-- update students set userage=100 where id=ids;--改
commit;
end;
都是入參,接收後對錶進行增刪改操作
呼叫
begin
mydemo07(10,'a','b','17');
end;
2.2 查詢
create or replace procedure mydemo08(ids in int, age out int)
as
begin
select userage into age from students where id=ids; --查
commit;
end;
根據傳入的id,查詢出年齡輸出
declare
ids int;
age int;
begin
ids:=1;
myDemo08(ids=>ids,age=>age);
dbms_output.put_line('age='||age);
end;
3 迴圈
3.1 for迴圈
create or replace procedure mydemo09
as
begin
for stu in (select * from students) loop
if (stu.id<5) then
dbms_output.put_line(stu.id);
end if;
end loop;
commit;
end;
呼叫
begin
mydemo09();
end;
3.2 while迴圈
create or replace procedure test_while_loop
as
n_count number := 0;
begin
while n_count < 10 loop
dbms_output.put_line(n_count);
n_count := n_count + 1;
end loop;
end;
在宣告的時候也可賦值
begin
test_while_loop();
end;