标签:plsql cursor sql oracle 数据库
表结构说明:
create table employee
(
id number(10) not null, -- 员工工号
salary number(10,2) default 0 not null, --薪水
name varchar2(24) not null --姓名
);
--开启控制台输出
set serverout on;
1.创建序列seq_employee,该序列每次取的时候它会自动增加,从1开始计数,不设最大值,并且一直累加,不循环。
-- Create sequence
create sequence SEQ_EMPLOYEE
minvalue 1
maxvalue 9999999999999999999999999999
start with 1
increment by 1
cache 20;
1. 写一个PL/SQL块,插入表user.employee中100条数据。插入该表中字段id用序列seq_employee实现,薪水和姓名字段可以任意填写。
declare
i number;
begin
for i in 1 .. 100
loop
insert into employee values(seq_employee.nextval,1950+i,‘匿名‘||to_char(i));
commit;
end loop;
end;
/
3.写一个语句块,在语句块中定义一个显式游标,按id升序排列,打印表employee中前十条数据。
declare
--定义一个显式游标,按id升序排列
cursor c is select id,salary,name from(select * from employee order by id) where rownum<11;
v_record c%rowtype;
begin
open c;
loop
fetch c into v_record;
exit when c%notfound;
dbms_output.put_line(to_char(v_record.id)||‘,‘||to_char(v_record.salary)||‘,‘||v_record.name);
end loop;
close c;
end;
/
4.创建存储过程p_employee,输入员工薪水范围,返回员工工号、姓名、薪水结果集,结果集按员工薪水升序排列。
create or replace procedure p_employee(iminsalary in number,imaxsalary in number)
is
begin
for x in(select id,salary,name from(select * from employee where salary between iminsalary and imaxsalary) order by salary)
loop
dbms_output.put_line(to_char(x.id)||to_char(x.salary)||x.name);
end loop;
end;
/
--调用存储过程
call p_employee(1951,1956);
exec p_employee(1951,1952);
5.创建函数f_employee实现更新员工薪水的功能,将薪水低于2000且姓王的员工薪水加5%,其他不变,更新成功则返回0,否则返回1。
create or replace function f_employee return number
is
begin
update employee set salary=salary+salary*0.05 where salary<2000 and name like ‘王%‘;
commit;
if sql%rowcount=0 then
return 1;
else
return 0;
end if;
end;
/
6.写一个匿名语句块,用于执行函数f_employee,并打印执行该函数的结果。
declare a number;
begin
a:=f_employee();
dbms_output.put_line(to_char(a));
end;
/
7.创建存储过程p_create_emp,用于判断表employee是否存在,如果存在则删除该表。
create or replace procedure p_create_emp
is
v_count number;
begin
select count(*) into v_count from user_tables where table_name=‘EMPLOYEE‘;
if v_count=0 then
return;
else
execute immediate ‘drop table employee‘;
end if;
end;
/
8.写一个匿名语句块,用于执行存储过程p_create_emp。
exec p_create_emp;
标签:plsql cursor sql oracle 数据库
原文地址:http://blog.csdn.net/sinat_26342009/article/details/46420241