常用PL/SQL代码收集

1、删除一个用户下的所有表;

begin 
for operation in (select 'DROP TABLE ' || table_name as droptable from user_tables) loop
    execute immediate  operation.droptable;
end loop;
end; 

 

2、嵌套表结合bulk collect的用法

declare
  type employee_table is table of employee%rowtype;
  employee_temp employee_table;
begin
  select * bulk collect into employee_temp from employee where id != 1;
  dbms_output.put_line(employee_temp(1).name);
end;

 

3、Fall和bulk collect用法一例

declare
  type employee_table is table of employee%rowtype;
  employee_temp employee_table;
begin
  select * bulk collect into employee_temp from employee where id != 1;
  forall i in 1..employee_temp.count 
      insert into employee1 values employee_temp(i);--此处要用行记录,而不能用行的字段
end;

 

4、 在DML的返回语句中使用BULK COLLECT子句

declare
  type employee_table is table of employee%rowtype;
  employee_temp employee_table;
begin
   delete from employee where id=&id  returning id,name bulk collect into employee_temp;
end;

 

5、显示游标使用一例

declare
  cursor emp_cursor is   --定义游标
    select id, name from employee;
  v_id   employee.id%type;
  v_name employee.name%type;
begin
  open emp_cursor;--打开游标
  loop
    fetch emp_cursor  --提取数据
      into v_id, v_name;
    dbms_output.put_line(v_id || v_name);
    exit when emp_cursor%notfound;
  end loop;
  close emp_cursor;--关闭游标
end;

 

6、游标FOR循环使用一例

declare
  cursor emp_cursor is
    select id, name from employee;
begin
  for emp_record in emp_cursor loop
    dbms_output.put_line(emp_record.id || emp_record.name);
  end loop;
end;
--直接在游标for循环中直接使用子查询
begin
  for emp_record in (select id,name from employee) loop
    dbms_output.put_line(emp_record.id || emp_record.name);
  end loop;
end;

 

7、游标变量使用一例

declare
  type emp_record_type is ref cursor return employee%rowtype;--定义游标变量
  emp_cursor emp_record_type;
  emp_record employee%rowtype;
begin
  open emp_cursor for select id, name from employee;--打开游标变量
  loop
    fetch emp_cursor into emp_record;--提取数据
    dbms_output.put_line(emp_record.id || emp_record.name);
    exit when emp_cursor%notfound;
  end loop;
  close emp_cursor;--关闭游标变量
end;

 

你可能感兴趣的:(sql)