PLSQL 基础语法(一)

变量声明与赋值

语法结构

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

案例演示

需求

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

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

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

语句

sql 复制代码
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;

变量select into 赋值

语法结构

csharp 复制代码
select 列名 into 变量名 from 表名 where 条件

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

案例演示

需求

查询id为100的员工月薪资

语句

sql 复制代码
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;

属性类型

引用型

记录型

相关异常处理

种类

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

语法结构

csharp 复制代码
exception
    when 异常类型 then
        异常处理逻辑

演示一

sql 复制代码
-- 异常处理
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;

演示二

sql 复制代码
-- 异常处理
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;
相关推荐
weixin_4462608523 分钟前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
ttwuai2 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
用户8356290780512 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
用户9931441579842 小时前
微服务框架中获取用户信息
后端
xuanWb2 小时前
手写一个 LLM API 网关:Anthropic 与 OpenAI 协议转换的完整实现
后端
苍何2 小时前
给 Codex 换皮肤这门生意,被我开源了
后端
用户8356290780512 小时前
Python 实现 Excel 命名范围(Named Range)的创建与管理
后端·python
程序员David2 小时前
我让 Claude 从架构文档一路干到代码,踩了三个坑才摸清边界
后端
Zane19942 小时前
并发 vs 并行:别再傻傻分不清了,一文讲透 Java 并发编程的第一课
java·后端