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;
相关推荐
Real_man31 分钟前
新物种与新法则:AI重塑开发与产品未来
前端·后端·面试
小马爱打代码1 小时前
Spring Boot:将应用部署到Kubernetes的完整指南
spring boot·后端·kubernetes
卜锦元1 小时前
Go中使用wire进行统一依赖注入管理
开发语言·后端·golang
SoniaChen333 小时前
Rust基础-part3-函数
开发语言·后端·rust
全干engineer3 小时前
Flask 入门教程:用 Python 快速搭建你的第一个 Web 应用
后端·python·flask·web
William一直在路上3 小时前
SpringBoot 拦截器和过滤器的区别
hive·spring boot·后端
小马爱打代码4 小时前
Spring Boot 3.4 :@Fallback 注解 - 让微服务容错更简单
spring boot·后端·微服务
曾曜4 小时前
PostgreSQL逻辑复制的原理和实践
后端
豌豆花下猫4 小时前
Python 潮流周刊#110:JIT 编译器两年回顾,AI 智能体工具大爆发(摘要)
后端·python·ai
轻语呢喃5 小时前
JavaScript :事件循环机制的深度解析
javascript·后端