Oracle--存储过程学习进阶

例1:该存储过程是向xuesheng 表中插入一行数

 create or replace procedure student_proc_no is
begin
insert into Student(id,name,C语言,软件工程) values (3, 'wangwu', 90, 90);
commit;
end student_proc_no;

例2:带游标的存储过程,遍历游标将数据存储到另一个表中

 create or replace procedure Score  --新增学分存储过程
is
begin
declare
cursor CourseCursor is --建立游标
select Id,
name,
score,
from wangou.Course;
c_row CourseCursor%rowtype;
begin
for c_row in CourseCursor loop 遍历上面建立的游标 ----插入对账单信息
insert into ScoreList
(                
id,
CourseName,
score,
)
values
(s_ScoreList.Nextval,
c_row.name,
c_row.score
); end loop;
end;
End;

例3: 存储过程实例:该存储过程的功能是:查询Student表中Status状态等于0的数据,之后一一插入到StudentCourseList表中,每插入一条记录之后将状态改为1;其中插入的过程中需要根据游标中的数据查询到其他表中相关数据插入到StudentCourseList表中。

 create or replace procedure StudentCoursePro  --新增学生课程存储过程
is
TmpCourseId number(9);--变量
TmpCourseName varchar2(50);--变量
Tmpdirection int;--变量
begin
declare
cursor StudentCursor is --建立游标
select Id,
StudentCode,
substr(CourseCode, -5) as CourseCode,--截取查询到的字段,负数从最右边开始截取,5代表截取位数为
                                 --5位。-5:代表从左右边开始向前(向左)截取5位数
Direction,
           createtime,
Status
from wangou.Student
where Status = 0
for update of Status;
c_row StudentCursor%rowtype;
begin
for c_row in StudentCursor loop 遍历上面建立的游标
--查询课程信息
select id,
Name
into TmpCourseId,
TmpCourseName
from Course
where code = c_row.CourseCode;--c_row.字段:为表中某一行的该字段的值 --
if (c_row.direction='A') then --当direction等于‘A’时,Tmpdirection=1
Tmpdirection:=1;
else                --当direction不等于‘A’时,Tmpdirection=2
Tmpdirection:=2;
end if; ----生成学生课程列表信息
insert into wangou.StudentCourseList--注意该表的ID为自动oracle的sequence序列号,因为该表是在另一个方案名下,
(--id,                 --无法引用到sequence,所以在另一个方案下提前建立了触发器,代码在文章末尾处给出
Name,
CourseID,
CouseName,
TearcherId,
direction,
date,

)
values
(--s_StudentCourseList.Nextval,
Name,TmpCourseID, TmpCourseName,
(select id from Tearcher where StudentID=c_row.ID),--查找老师信息
Tmpdirection,
to_date(c_row.createtime,'yyyy-mm-dd hh24:mi:ss'),--将createtime时间转换为需要的时间格式


); ----更新对账单.处理状态 = 1(已处理)。
update wangou.Student    --wangou为方案名
set Status = 1
WHERE CURRENT OF StudentCursor;
end loop;
end;
End;

 触发器代码:

该触发器的功能是:当有数据插入到StudentCourseList表中之前,为该表的ID(即“:new.id”)预先给个值,

         值即为该表的序列号S_StudentCourseList.NEXTVAL

 create or replace trigger StudentCourseListTri
before insert on StudentCourseList --当有数据插入StudentList表之前
for each row
declare
nextid NUMBER;--变量
begin
SELECT S_StudentCourseList.NEXTVAL
  INTO nextid
  FROM dual;
:new.id:=nextid;
end StudentCourseListTri;
上一篇:【学习】Windows PE文件学习(一:导出表)


下一篇:Winter-1-C A + B II 解题报告及测试数据