ID
NAME
SALARY
100
Jacky
5600
101
Rose
3000
102
John
4500 要求:
1.创建该表并输入相应的数据。
2.根据特定ID可以查询到其姓名和薪水的信息。
3.根据大于特定的薪水的查询相应的员工信息。
根据前面的要求,可以分别创建三个过程(均使用动态SQL)来实现:
过程一:
create or replace procedure create_table as begin execute immediate ' create table emp(id number, name varchar2(10) salary number; )'; --动态SQL为DDL语句 insert into emp values (100,'jacky',5600); insert into emp values (101,'rose',3000); insert into emp values (102,'john',4500); end create_table; 过程二:
create or replace procedure find_info(p_id number) as v_name varchar2(10); v_salary number; begin execute immediate ' select name,salary from emp where id=:1' using p_id returning into v_name,v_salary; --动态SQL为查询语句 dbms_output.put_line(v_name ||'的收入为:'||to_char(v_salary)); exception when others then dbms_output.put_line('找不到相应数据'); end find_info; 过程三:
create or replace procedure find_emp(p_salary number) as r_emp emp%rowtype; type c_type is ref cursor; c1 c_type; begin open c1 for ' select * from emp where salary >:1' using p_salary; loop fetch c1 into r_emp; exit when c1%notfound; dbms_output.put_line('薪水大于‘||to_char(p_salary)||’的员工为:‘); dbms_output.put_line('ID为'to_char(r_emp)||' 其姓名为:'||r_emp.name); end loop; close c1; end create_table; 注意:在过程二中的动态SQL语句使用了占位符“:1“,其实它相当于函数的形式参数,使用”:“作为前缀,然后使用using语句将p_id在运行时刻将:1给替换掉,这里p_id相当于函数里的实参。另外过程三中打开的游标为动态游标,它也属于动态SQL的范畴,其整个编译和开发的过程与execute immediate执行的过程很类似,这里就不在赘述了。