PL/SQL基础语法赋值循环游标etc

PL/SQL基础语法赋值循环游标etc

-- pl/sql语法
declare
       age number(3);
       is_true boolean := false;
begin
       age := 100;--赋值
       dbms_output.put_line('hei呆');
       dbms_output.put_line(age);
       --dbms_output.put_line(is_true);boolean不能直接输出
       dbms_output.put_line(sys.diutil.bool_to_int(is_true));--转成int
       dbms_output.put_line(
           case
              when is_true then 'TRUE'
              when is_true is null then 'NULL'
              else 'FALSE'
            end
       );
end;


declare
  pname emp.ename%type; -- 引用型变量 引用表的字段的类型
begin
  --从数据库中获取数据并赋值给变量
  select t.ename into pname from emp t where t.empno = 7369;
  dbms_output.put_line(pname);
end;
     
declare
  emprec emp%rowtype;--记录型变量 选取某个表作为类型
begin
  select t.* into emprec from emp t where t.empno = 7369;
  dbms_output.put_line(emprec.empno|| '  '|| emprec.ename || ' ' || emprec.job);
end; -- 7369 SMITH CLERK
         
 select * from emp where empno = 7369;
 
 -- while循环loop
 declare
   pnum number(4) := 0;
 begin
   while pnum < 10 loop --while成立时执行
     dbms_output.put_line(pnum);
     pnum := pnum + 1;
   end loop;
 end;


declare
  pnum number(4) := 0;
begin
  loop
   exit when pnum > 10;--条件成立时推出循环
   dbms_output.put_line(pnum);
   pnum :=pnum+1;
   end loop;
end;



--for in 循环
declare
  pnum number(4);
begin
  for pnum in 1 .. 10 loop -- pnum从1递增到10 循环10次
    dbms_output.put_line(pnum);
  end loop;
end;


--游标
declare
  cursor pc is
    select * from emp;
    temp emp%rowtype;--定义数据类型
begin
  open pc;--打开游标
  loop
    fetch pc
      into temp;
    exit when pc%notfound;
    dbms_output.put_line(temp.empno || ' ' || ' ' || temp.ename);
  end loop;
  close pc; --关闭游标 不然影响性能
end;


--根据job等级分别加薪不同幅度
declare
  cursor cur is
    select * from emp;
  temp   emp%rowtype;
  addsal number(4); --加薪幅度
begin
  open cur;
  loop
    fetch cur into temp;
    exit when cur%notfound;
    if temp.job = 'BOSS' then
      addsal := 200;
    elsif temp.job = 'MANAGER' then--elsif 不是else if
      addsal := 100;
    else
      addsal := 0;
    end if;
    update emp t set t.sal = t.sal + addsal where t.empno = temp.empno; -- 修改记录
  end loop;
close cur; --关闭游标
commit; --提交事务 plsql中修改删除新增都要手动commit
end;


-- 游标接收参数
declare
        cursor cur(dno emp.deptno%type) is
        select * from emp t where t.deptno = dno;
        temp emp%rowtype;
begin
  open cur(2);
  loop fetch cur into temp;--根据传入参数选择指定部门编号的记录赋给temp
    exit when cur%notfound;
    update emp t set t.sal = t.sal + 10000 where t.empno = temp.empno;--根据员工id修改记录
   end loop;
   close cur;
   commit;
end;
用plsql处理数据要方便了很多啊~~~
(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐