Oracle中使用存储过程实现几个实例_入门级

刚开始我也不会写Oracle的存储过程,以前顶多用过SQLServer,工作时偶尔要处理上万条的数据,有时候不得不手动处理,有时候,可以想办法使用工具解析导入数据库,虽然存储过程不能很好的处理海量数据,这只是我业余看到就学习总结了一下。由浅入深的实现了几个实例,看完了,就可以简单的掌握Oracle存储过程的些许语法了。

1. 先在库里新建个表


create  table  new_table_test (num1 int,num2 int,num3 int)

2.简单的不带循环的插入数据到表里

create or replace procedure myproc
is
num integer; 
begin 
	num:=1;
	begin	
		insert into new_table_test values(num,2,3);
	end;	
end myproc;

注意:变量num类型为Integer;

3.在2的基础上实现变量值赋值时的处理:

create or replace procedure myproc
is
num integer; 
begin 
	num:=1; 
	begin
		num:=num+1;
		insert into new_table_test values(num,2,3); 
    	 end;
end myproc;

注意:不要多加个set,变量记得加个冒号。

4.使用while循环进行插入1000行数据

知识点:while循环使用loop,最后使用end
loop;结束,对于首变量赋值时不要忘记加冒号。
等号左边的变量也要加冒号。

create or replace procedure myproc
is
num integer; 
begin 
num:=1; 
	while num <= 1000 LOOP
	begin
		insert into new_table_test values(num,2,3); 
		num:=num+1;
	end;
	end LOOP;
end myproc;

5.调用存储过程

【call 存储过程名】调用存储过程

call myproc();

6.用for…in 使用cursor.
知识点:打印游标的值的方式是:cursor.列名。

create or replace procedure certifipro
as 
CURSOR cursor_1 is select distinct certificateid from FIDataDistilledInfo; 
column1 varchar2(7);
begin
	for
	column1 in cursor_1 LOOP
		begin
			dbms_output.put_line(column1.certificateid);  
		end;    
	end LOOP;
end certifipro;

–调用存储过程

call certifipro();   

7.使用cursor,cursor的结果集是下一个sql语句的条件,打印一列

create or replace procedure certifipro
as 
CURSOR cursor_1 is select distinct certificateid from FIDataDistilledInfo; 
column1 varchar2(7);
column2 varchar2(50);
begin
for
column1 in cursor_1 LOOP
	begin
		select
		certificatename into column2 from FICertificateTypeDef  where
		certificateid=column1.certificateid;   
		dbms_output.put_line(column2);     
		end;    
end   LOOP;
end certifipro;


–调用存储过程


call certifipro();

8.使用cursor,cursor的一列结果集是下一个sql语句的条件,打印全部列

----先创建一个存储查询的最后结果的表结构:


create table new1 as select * from FICertificateTypeDef where 1<>1;

–存储过程,将结果保存到一个表,可以保存全部的信息。这里不可以单选几列。与insert语句的格式有关系。必须保存全部。


create or replace procedure certifipro
as 
CURSOR cursor_1 is select distinct certificateid from FIDataDistilledInfo; 
column1 varchar2(7);
begin  for  column1 in cursor_1 LOOP
    begin
	 insert into new1 select * from FICertificateTypeDef where certificateid=column1.certificateid;      
    end;    
  end  LOOP;
end certifipro;

–调用存储过程

call certifipro();

查看得到的结果集new1:

select * from new1;

9.删除存储过程

drop procedure 存储过程名;

以上存储过程都可正常运行,通过学习语法,简单的做了上面的练习,对于存储过程的使用可以简单掌握。

在练习时,对于命名我只简单的命名,便于用于测试,未按照标准命名,如果在自己的工作中使用,还是要按照命名规范命名。

存储过程的使用,一点语法错误,都会导致运行不成功,这种方式感兴趣的可以研究一下,在工作中,有的还是会用到存储过程进行批处理。

猜你喜欢

转载自blog.csdn.net/qq_37887131/article/details/86541316