PLSQL 基础语法(一)

642 阅读1分钟

变量声明与赋值

语法结构

[delare
     -- 申明变量
 ]
 begin
     -- 代码逻辑
 [exception
     -- 异常处理
 ]
end;

案例演示

需求

  1. 声明变量水费单价、水费字数、吨数、金额

  2. 对水费单价、字数、进行赋值。吨数根据水费字数换算,规则为水费字数除以1000,并且四舍五入,保留两位小数。计算金额,金额单价*吨数

  3. 输出单价、数量和金额

语句

declare
  v_price number(10,2); --单价
  v_usenum number; --水费字数
  v_usenum2 number; --吨数
  v_money number(10,2); --金额
begin
  v_price:=2.45; --单价赋值
  v_usenum:=9123; --水费字数
  v_usenum2:=round(v_usenum/1000,2);--吨数
  v_money:=v_price*v_usenum2;--金额
  
  DBMS_OUTPUT.put_line('金额:'||v_money);
end;

image.png

变量select into 赋值

语法结构

select 列名 into 变量名 from 表名 where 条件

注: 结果必须是一条数据,有多条和没有数据都会报错

案例演示

需求

查询id为100的员工月薪资

image.png

语句

declare 
  e_salary number(10,2); --月工资
begin
  select salary into e_salary from employees
  where employee_id = 100;   
  DBMS_OUTPUT.put_line('工资:'||e_salary);
end;

image.png

属性类型

引用型

image.png

记录型

image.png

相关异常处理

种类

  1. NO_DATA_FOUND:使用 select into 未返回行
  2. TOO_MANY_ROWS:执行 select into 时,结果集超过一行

语法结构

exception
    when 异常类型 then
        异常处理逻辑

演示一

-- 异常处理
declare 
  employee employees%rowtype;
begin
  select * into employee from employees where employee_id = 12345;   
  DBMS_OUTPUT.put_line('工资:'||employee.salary);
exception
  when no_data_found then
     DBMS_OUTPUT.put_line('没有找到该用户');
end;

image.png

演示二

-- 异常处理
declare 
  employee employees%rowtype;
begin
  select * into employee from employees ;   
  DBMS_OUTPUT.put_line('工资:'||employee.salary);
exception
  when no_data_found then
     DBMS_OUTPUT.put_line('没有找到该用户');
 when too_many_rows then
     DBMS_OUTPUT.put_line('存在多条符合条件的数据');
end;

image.png