PLSQL语法基础

来源:互联网 发布:mac qq怎么发文件夹 编辑:程序博客网 时间:2024/06/05 07:34

PLSQL语法基础

–pl/sql块

begin  dbms_output.put_line('hello world');end;

–声明变量并赋值

declare  sname varchar2(20) :='jerry';--赋值初始化begin  sname:=sname ||' and Tom'; --重新赋值  dbms_output.put_line(sname);end;

–从数据库中查出结果 赋给变量

declare   sname varchar2(20) default'jerry';begin  select ename into sname from emp where empno=7902;  dbms_output.put_line(sname);end;

–从控制台输入变量值

declare  v_ename varchar2(10);  v_empno number;begin  v_empno :=&no;  select ename into v_ename from emp where empno=v_empno;  dbms_output.put_line('用户名'||v_ename);exception  when no_data_found then    dbms_output.put_line('未发现该编号');end;/ 

–声明常量
–计算圆的面积

declare    pi constant number:=3.14;    r number default 3;    area number;begin  area := pi*r*r;  dbms_output.put_line(area);end;/ 

–Oracle中有两种属性数据类型 %type 和 %rowtype
–%rowtype 引用数据库表中的一行作为数据类型

declare  myemp emp%rowtype;begin  select * into myemp from emp where empno=7934;  dbms_output.put_line(myemp.ename);end;

–%type 引用某个变量或者数据库的列的类型作为数据类型

declare  v_sal emp.sal%type;  v_mysal number(4):=3000;  v_totalsal v_mysal%type;begin  select sal into v_sal from emp where empno=7934;  v_totalsal:=v_mysal+v_sal;  dbms_output.put_line(v_sal ||'  '||v_totalsal);end;/

–流程控制
–查询JAMES的工资,如果大于900元,则发奖金800元。

declare  newSal emp.sal%type;begin  select sal into newSal from emp where ename='JAMES';  if newSal>900 then    update emp set comm=comm+800 where ename='JAMES';  end if;  commit;end;/

–异常处理
–更新指定员工工资,如工资小于1500,则加100;

declare  v_empno emp.empno%type:=&numb;  v_sal emp.sal%type;begin  select sal into v_sal from emp where empno=v_empno;  if v_sal<1500 then    update emp set sal=sal+100 where empno = v_empno;    dbms_output.put_line('编码为'||v_empno||'的员工数据已更新');  else    dbms_output.put_line('编码为'||v_empno||'的员工工资已超过规定值');  end if;  exception    when no_data_found then      dbms_output.put_line('数据库没有编码为'||v_empno||'的员工');    when too_many_rows then      dbms_output.put_line('程序运行错误,请使用游标');    when others then      dbms_output.put_line('发生其他错误');end;/
原创粉丝点击