表結構說明:
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;