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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值