一.数据库初始化脚本
-- Create table 学生信息
drop table HAND_STUDENT;
create table HAND_STUDENT
(
STUDENT_NO VARCHAR2(10) not null,
STUDENT_NAME VARCHAR2(20),
STUDENT_AGE NUMBER(2),
STUDENT_GENDER VARCHAR2(5)
);
-- Add comments to the table
comment on table HAND_STUDENT
is '学生信息表';
-- Add comments to the columns
comment on column HAND_STUDENT.STUDENT_NO
is '学号';
comment on column HAND_STUDENT.STUDENT_NAME
is '姓名';
comment on column HAND_STUDENT.STUDENT_AGE
is '年龄';
comment on column HAND_STUDENT.STUDENT_GENDER
is '性别';
-- Create/Recreate primary, unique and foreign key constraints
alter table HAND_STUDENT add primary key (STUDENT_NO); -- Create table 教师信息表
drop table HAND_TEACHER;
create table HAND_TEACHER
(
TEACHER_NO VARCHAR2(10) not null,
TEACHER_NAME VARCHAR2(20),
MANAGER_NO VARCHAR2(10)
);
-- Add comments to the table
comment on table HAND_TEACHER
is '教师信息表';
-- Add comments to the columns
comment on column HAND_TEACHER.TEACHER_NO
is '教师编号';
comment on column HAND_TEACHER.TEACHER_NAME
is '教师名称';
comment on column HAND_TEACHER.MANAGER_NO
is '上级编号';
-- Create/Recreate primary, unique and foreign key constraints
alter table HAND_TEACHER add primary key (TEACHER_NO); -- Create table 课程信息表
drop table HAND_COURSE;
create table HAND_COURSE
(
COURSE_NO VARCHAR2(10) not null,
COURSE_NAME VARCHAR2(20),
TEACHER_NO VARCHAR2(20) not null
);
-- Add comments to the table
comment on table HAND_COURSE
is '课程信息表';
-- Add comments to the columns
comment on column HAND_COURSE.COURSE_NO
is '课程号';
comment on column HAND_COURSE.COURSE_NAME
is '课程名称';
comment on column HAND_COURSE.TEACHER_NO
is '教师编号';
-- Create/Recreate primary, unique and foreign key constraints
alter table HAND_COURSE add constraint PK_COURSE primary key (COURSE_NO, TEACHER_NO); -- Create table 成绩信息表
drop table HAND_STUDENT_CORE;
create table HAND_STUDENT_CORE
(
STUDENT_NO VARCHAR2(10) not null,
COURSE_NO VARCHAR2(10) not null,
CORE NUMBER(4,2)
);
-- Add comments to the table
comment on table HAND_STUDENT_CORE
is '学生成绩表';
-- Add comments to the columns
comment on column HAND_STUDENT_CORE.STUDENT_NO
is '学号';
comment on column HAND_STUDENT_CORE.COURSE_NO
is '课程号';
comment on column HAND_STUDENT_CORE.CORE
is '分数';
-- Create/Recreate primary, unique and foreign key constraints
alter table HAND_STUDENT_CORE add constraint PK_SC primary key (STUDENT_NO, COURSE_NO); -- Create table 学生历史信息表
drop table HAND_STUDENT_HIS;
create table HAND_STUDENT_HIS
(
STUDENT_NO VARCHAR2(10) not null,
STUDENT_NAME VARCHAR2(20),
STUDENT_AGE NUMBER(2),
STUDENT_GENDER VARCHAR2(5),
LAST_UPDATE_DATE DATE,
STATUS VARCHAR2(5)
);
-- Add comments to the table
comment on table HAND_STUDENT_HIS
is '学生信息历史表';
-- Add comments to the columns
comment on column HAND_STUDENT_HIS.STUDENT_NO
is '学号';
comment on column HAND_STUDENT_HIS.STUDENT_NAME
is '姓名';
comment on column HAND_STUDENT_HIS.STUDENT_AGE
is '年龄';
comment on column HAND_STUDENT_HIS.STUDENT_GENDER
is '性别';
comment on column HAND_STUDENT_HIS.LAST_UPDATE_DATE
is '最后更新时间';
comment on column HAND_STUDENT_HIS.STATUS
is '状态'; -- Create table 日志信息表
drop table HAND_LOG;
create table HAND_LOG
(
CODE VARCHAR2(240) not null,
MSG VARCHAR2(240) not null,
KEY1 VARCHAR2(240),
KEY2 VARCHAR2(240),
KEY3 VARCHAR2(240),
KEY4 VARCHAR2(240),
KEY5 VARCHAR2(240)
);
-- Add comments to the table
comment on table HAND_LOG
is '日志信息表';
-- Add comments to the columns
comment on column HAND_LOG.CODE
is '编号';
comment on column HAND_LOG.MSG
is '消息';
comment on column HAND_LOG.KEY1
is '关键字1';
comment on column HAND_LOG.KEY2
is '关键字2';
comment on column HAND_LOG.KEY3
is '关键字3';
comment on column HAND_LOG.KEY4
is '关键字4';
comment on column HAND_LOG.KEY5
is '关键字5'; /*******初始化学生表的数据******/
insert into HAND_STUDENT values ('s001','张三',23,'男');
insert into HAND_STUDENT values ('s002','李四',23,'男');
insert into HAND_STUDENT values ('s003','吴鹏',25,'男');
insert into HAND_STUDENT values ('s004','琴沁',20,'女');
insert into HAND_STUDENT values ('s005','王丽',20,'女');
insert into HAND_STUDENT values ('s006','李波',21,'男');
insert into HAND_STUDENT values ('s007','刘玉',21,'男');
insert into HAND_STUDENT values ('s008','萧蓉',21,'女');
insert into HAND_STUDENT values ('s009','陈萧晓',23,'女');
insert into HAND_STUDENT values ('s010','陈美',22,'女');
commit;
/******************初始化教师表***********************/
insert into HAND_TEACHER values ('t001', '刘阳','');
insert into HAND_TEACHER values ('t002', '谌燕','t001');
insert into HAND_TEACHER values ('t003', '胡明星','t002');
commit;
/***************初始化课程表****************************/
insert into HAND_COURSE values ('c001','J2SE','t002');
insert into HAND_COURSE values ('c002','Java Web','t002');
insert into HAND_COURSE values ('c003','SSH','t001');
insert into HAND_COURSE values ('c004','Oracle','t001');
insert into HAND_COURSE values ('c005','SQL SERVER 2005','t003');
insert into HAND_COURSE values ('c006','C#','t003');
insert into HAND_COURSE values ('c007','JavaScript','t002');
insert into HAND_COURSE values ('c008','DIV+CSS','t001');
insert into HAND_COURSE values ('c009','PHP','t003');
insert into HAND_COURSE values ('c010','EJB3.0','t002');
insert into HAND_COURSE values ('c011','PHP','t004');
commit;
/***************初始化成绩表***********************/
insert into HAND_STUDENT_CORE values ('s001','c001',58.9);
insert into HAND_STUDENT_CORE values ('s002','c001',80.9);
insert into HAND_STUDENT_CORE values ('s003','c001',81.9);
insert into HAND_STUDENT_CORE values ('s004','c001',60.9);
insert into HAND_STUDENT_CORE values ('s001','c002',82.9);
insert into HAND_STUDENT_CORE values ('s002','c002',72.9);
insert into HAND_STUDENT_CORE values ('s003','c002',81.9);
insert into HAND_STUDENT_CORE values ('s001','c003','');
insert into HAND_STUDENT_CORE values ('s003','c011',81.9);
insert into HAND_STUDENT_CORE values ('s001','c011','');
commit;
二.PL/SQL练习题
1.创建一个 package,命名为 cux_exam_工号_pkg,包含以下内容:
1.1声明一个 recoder 数据类型命名为 type_studens_rec,包含以下字段:
1.2 基于上面的记录声明一个内存表类型,命名为 type_studens_tbl。
1.3创建一个方法,返回类型为 type_studens_tbl,取出分数低于课程平均分 的学生信息:学号、姓名、课程编号、课程名、教师、分数、课程平均分、 课程最高分、最低分。
1.4创建一个过程,调用上面的方法,输出这些学生中,给所有成绩低于平均分 的学生加 1 分(更新成绩表),如果加分后的学生成绩低于 60 分,则输出这 个学生的信息。处理成功则返回 S 状态并提交事物;失败则返回 E 状态及 回错误消息,同时回滚事物。
1.5创建一个方法,根据参数的教师编号,返回这个教师的直接领导的教师编 号。如果不存在,返回-1, 如果存在多条记录,返回-2,如果存在其他异 常,返回-3。
1.6创建一个公共方法,根据参数 课程编号,返回该课程学生的及格率,返回 类型为数字,保留两位小数(及格率=课程成绩在 60 分以上的同学人数/课 程总人数)。
1.7写一个匿名块,创建一张临时表,hand_teacher_temp(动态 SQL), 结构 与 hand_teacher 相同。取所有课程及格率高于 50%的教师信息,插入到hand_teacher_temp 表中。(使用前面程序中求及格率的函数)。
1.8 写一个匿名块,更新学生所选课程的成绩。如果存在课程成绩在 60 分以 上,则对原成绩降分 2%,输出学生编号,课程编号以及更新后的成绩(用 returning into )。
题解:
包头(1.1~1.6):
create or replace package cux_exam_xxxx_pkg is
-- 1. 定义数据类型
type score_data_type is record(
student_no hand_student.student_no%type,
student_name hand_student.student_name%type,
student_age hand_student.student_age%type,
student_gender hand_student.student_gender%type,
course_no hand_course.course_no%type,
course_name hand_course.course_name%type,
teacher_name hand_teacher.teacher_name%type,
core hand_student_core.core%type,
avg_core hand_student_core.core%type,
max_core hand_student_core.core%type,
min_core hand_student_core.core%type);
-- 2. 定义内存表类型 type_studens_tbl
TYPE type_studens_tbl IS TABLE OF studens_rec%ROWTYPE INDEX BY
BINARY_INTEGER;
-- 3. 获得低于平均分数的学⽣生信息
function get_grounded_info return type_studens_tbl;
-- 4. 分数调整
procedure score_adjustment(p_std_score in number,
x_return_status out nocopy varchar2,
x_msg_data out nocopy varchar2);
-- 5. 查询教师的直接领导
function get_manager(p_teacher_no in varchar2) return varchar2 ;
-- 6. 查询课程的及格率
function get_course_pass_rate(p_course_no in varchar2) return
number ;
end cux_exam_xxxx_pkg;
包体(1.1~1.6):
create or replace package body cux_exam_xxxx_pkg is
-- 3. 获得低于平均分数的学⽣生信息
function get_grounded_info return type_studens_tbl is
l_studens_tbl type_studens_tbl;
begin
-- 计算每⻔门课程的平均分,并取出所有成绩低于平均分的学⽣生
select *
from (select hs.student_no,
hs.student_name,
hs.student_age,
hs.student_gender,
hc.course_no,
hc.course_name,
ht.teacher_name,
hsc.core,
round(avg(hsc.core) over(partition by
hsc.course_no), 2) avg_core,
max(hsc.core) over(partition by hsc.course_no)
max_core,
min(hsc.core) over(partition by hsc.course_no)
min_core
from hand_course hc,
hand_student hs,
hand_student_core hsc,
hand_teacher ht
where hc.course_no = hsc.course_no
and hs.student_no = hsc.student_no
and hc.teacher_no = ht.teacher_no)
BULK COLLECT into l_studens_tbl
where core < avg_core;
return l_studens_tbl;
end get_grounded_info;
-- 4. 分数调整
procedure score_adjustment(p_std_score in number,
x_return_status out nocopy varchar2,
x_msg_data out nocopy varchar2) is
l_data_cur ref_cursor;
l_data_rec score_data_type;
l_new_score number;
l_savepoint_name varchar2(30) := 'sp_score_adjustment';
begin
x_return_status := 'S';
x_msg_data := null;
savepoint l_savepoint_name;
l_data_cur := get_grounded_info;
loop
fetch l_data_cur
into l_data_rec;
exit when l_data_cur%notfound;
update hand_student_core hsc
set hsc.core = nvl(hsc.core, 0) + 1
where hsc.student_no = l_data_rec.student_no
and hsc.course_no = l_data_rec.course_no
returning hsc.core into l_new_score;
if l_new_score < nvl(p_std_score, 60) then
dbms_output.put_line('Student No.: ' ||
l_data_rec.student_no ||
', Student Name: ' ||
l_data_rec.student_name ||
', Course Name: ' ||
l_data_rec.course_name ||
', Teacher Name: ' ||
l_data_rec.teacher_name ||
', Score: ' || l_data_rec.core ||
', Avg score: ' || l_data_rec.avg_core
||
', Max score: ' || l_data_rec.max_core
||
', Min score: ' ||
l_data_rec.min_core);
end if;
end loop;
commit;
exception
when others then
rollback to l_savepoint_name;
x_return_status := 'E';
x_msg_data := substr(sqlerrm, 1, 2000);
end score_adjustment;
-- 5. 查询教师的直接领导
function get_manager(p_teacher_no in varchar2) return varchar2 is
l_teacher_no hand_teacher.teacher_no%type;
begin
select ht.teacher_no
into l_teacher_no
from hand_teacher ht
where level = 2
connect by ht.teacher_no = prior ht.manager_no
start with ht.teacher_no = p_teacher_no;
return l_teacher_no;
exception
when no_data_found then
return '-1';
when too_many_rows then
return '-2';
when others then
return '-3';
end get_manager;
-- 6. 查询课程及格率
function get_course_pass_rate(p_course_no in varchar2) return
number is
l_passed_count number;
l_total_count number;
l_course_pass_rate number;
begin
select sum(case
when hsc.core > 60
then 1
else
0
end) passed_count, count(1) total_count
Into l_passed_count, l_total_count
from hand_student_core hsc
where hsc.course_no = p_course_no;
l_course_pass_rate := round(l_passed_count/l_total_count,2);
return l_course_pass_rate;
exception
when others then
return null;
end get_course_pass_rate;
end cux_exam_XXXX_pkg;
1.7:
-- 7.取所有课程及格率⾼高于50%的教师信息,插⼊入到 hand_teacher_temp 表中。
declare
l_count number;
begin
select count(1)
into l_count
from all_tables t
where t.TABLE_NAME = 'HAND_TEACHER_TEMP';
if l_count > 0 then
execute immediate 'DROP TABLE HAND_TEACHER_TEMP';
end if;
execute immediate 'CREATE TABLE HAND_TEACHER_TEMP AS ' ||
insert hand_teacher_temp
select *
from hand_teacher ht
where not exists(
select 1
from hand_course hc
where cux_exam_xxxx_pkg.get_grounded_info(hc.course_no)
<0.5
and hc.teacher_no = ht.teacher_no)';
exception
when others then
dbms_output.put_line(sqlcode || '-' || sqlerrm);
end;
1.8:
-- 8. 写⼀一个匿匿名块,更更新学⽣生所选课程的成绩。如果存在课程成绩在 60 分以 上,则对
原成绩降分 2%,输出学⽣生编号,课程编号以及更更新后的成绩(⽤用 returning into )(10
分)
Declare
TYPE type_student_core_tb IS TABLE OF hand_student_core%ROWTYPE;
l_student_core_tb type_student_core_tb;
begin
Update hand_student_core t
set t.core = t.core * 0.98
Where t.core >60
RETURNING student_no ,course_no, core BULK COLLECT INTO
l_student_core_tb;
FOR i IN l_student_core_tb.FIRST .. l_student_core_tb.LAST
LOOP
DBMS_OUTPUT.PUT_LINE( l_student_core_tb(i). student_no || ' '||
l_student_core_tb(i). course_no || ' '|| l_student_core_tb(i).
core );
END LOOP;
commit;
exception
when others then
rollback;
dbms_output.put_line(sqlcode || '-' || sqlerrm);
end;
小结:
注函数和存储过程的区别:函数有返回值,存储过程没有返回值,函数参数只能是INT类型(传入参数),存储过程可以是INT,OUT,IN OUT;
大多数SQL函数能在PL/SQL中过程语句中使用,如单行的数值和字符串函数、数据类型转换函数、日期函数、时间函数、求最大、最小值的 GREATEST, LEAST 函数等,但是有些函数不能再PL/SQL中使用,如Decode函数、分组函数(AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE)等;
PLSQL的块是可以嵌套的,变量的作用范围与其他语言类似 ,如果同名,想要访问外层的需要使用outer关键字;
PLSQL中常用的自定义类型就两种: 记录类型、PLSQL内存表类型(根据表中的数据字段的简单和复杂 程度又可分别实现类似于简单数组和记录数组的功能);
意外处理等,内置异常,以及raise_application_error()函数等注意。。。
2.(1) 创建一个历史表 hand_teacher_his, 其中包括 hand_teacher 表的所 有字段, 新增 last_update_date(处理日期)以及 operation(操作类 型)两列 。
(2) 在 hand_teacher 表上面创建一个触发器,记录表的新增,更新(记录更 新前的数据)和删除(记录删除前的数据)操作,并记录操作类型和处理日期。
题解:
(1):
-- 2-1. 创建⼀一个 hand_teacher_his 历史表
create table hand_teacher_his
as
select ht.*, sysdate last_update_date, 'U' operation
from hand_teacher ht
where 1=-1;
(2):
-- 2-2. 在 hand_teacher 表上新建⼀一个触发器器
create or replace trigger hand_teacher_tgr1
after insert or update or delete on hand_teacher
for each row
declare
begin
if inserting then
insert into hand_teacher_his
values(:new.teacher_no, :new.teacher_name, :new.manager_no,
sysdate, 'I');
elsif updating then
insert into hand_teacher_his
values(:old.teacher_no, :old.teacher_name, :old.manager_no,
sysdate, 'U');
elsif deleting then
insert into hand_teacher_his
values(:old.teacher_no, :old.teacher_name, :old.manager_no,
sysdate, 'D');
end if;
exception
when others then
raise_application_error(-20005, sqlcode ||'-' ||sqlerrm );
end;
小结:
触发器注意:时机:Before 或者 After 或 Instead of 事件:Insert 或 Update 或 Delete 对象:表名(或视图名) 类型:Row 或者 Statement级; 条件:满足特定Where条件才执行; 内容:通常是一段PLSQL块代码;
重点注意: Instead of : 用Trigger的内容替换 事件本身的动作 Row级:SQL语句影响到的每一行都会引发Trigger Statement级:一句SQL语句引发一次,不管它影响多少行(甚至0行)。
3. 写一个匿名块,在 system(system/manager)用户下执行。 新建一个 directory : HAND_DIR_TEMP_XXXX , 物理地址为虚拟机的 c:\temp 目录, 并授权 读写 权限给 student1 用户,然后将 hand_exam_data.txt 这个 文件放到 c:\temp 目录下。(xxxx 为自己的工号):
-- 3. 使⽤用system ⽤用户新建⼀一个 directory
begin
execute immediate 'create or replace directory HAND_DIR_TEMP as
''c:\temp''';
execute immediate 'grant read ,write on directory HAND_DIR_TEMP to
student1';
end;
小结:
Oracle Directory是为了便于控制Bfile存储的安全性;
在Oracle 内部创建的 Directory 默认的所有者是sys, 并有DBA( 或者是另一个拥有 CREATE ANY DIRECTORY 权限的用户)创建;Directory 对象可以像表那样给其他用户赋权。
4.从 hand_exam_data.txt 文件读取内容并导入到 hand_teacher 表。要求: (1) 从数据文件中读取数据,并按照逗号分隔符进行拆分,提取字段的值。 (2) 去掉数据中的双引号 (3) 将处理后的数据,插入到 hand_teacher 表 :
-- 3. 从hand_exam_data.txt⽂文件读取内容并导⼊入到 hand_teacher 表
declare
l_line VARCHAR2(1023);
fid UTL_FILE.FILE_TYPE;
l_data_rec hand_teacher%rowtype;
procedure split_columns(p_data_str in varchar2,
x_data_rec out hand_teacher%rowtype) is
l_substr varchar2(2000);
l_instr number;
begin
if p_data_str is null then
return;
end if;
l_substr := p_data_str;
l_instr := instr(l_substr, ',');
x_data_rec.teacher_no := trim(replace(substr(l_substr, 1,
l_instr - 1),'"',''));
-- 提取teacher_name
l_substr := substr(l_substr, l_instr + 1);
l_instr := instr(l_substr, ',');
x_data_rec.teacher_name := trim(replace(substr(l_substr, 1,
l_instr - 1),'"',''));
-- 提取manager_no
l_substr := substr(l_substr, l_instr + 1);
l_instr := instr(l_substr, ',');
x_data_rec.manager_no := trim(replace(l_substr,'"',''));
end;
BEGIN
BEGIN
fid := UTL_FILE.FOPEN('HAND_DIR_TEMP', 'hand_exam_data.txt',
'R');
loop
UTL_FILE.GET_LINE(fid, l_line);
dbms_output.put_line(l_line);
split_columns(l_line, l_data_rec);
if l_data_rec.teacher_no is not null then
insert into hand_teacher values l_data_rec;
end if;
end loop;
utl_file.fclose(fid);
EXCEPTION
WHEN NO_DATA_FOUND THEN
if utl_file.is_open(fid) then
utl_file.fclose(fid);
end if;
END;
commit;
EXCEPTION
WHEN others THEN
rollback;
dbms_output.put_line(sqlcode || '-' || sqlerrm);
END;
小结:
这里注意打开文件函数 UTL_FILE.FOPEN,读取内容函数 UTL_FILE.GET_LINE,以及何时不在读取(为null),以及异常处理,内容格式处理。