MySQL的存储过程

MySQL的存储过程

存储过程的概念

完成特定功能的sql语句的集合。把定义好的sql集合在一个特定的sql函数中每次执行调用函数即可。还可以实现传参的调用。

存储过程的作用

执行速度比sql语句执行的速度更快,执行的效率也更高。

客户端可以随时调用发放,也可以随时修改。

可以对数据库内做任何操作。

存储过程的语法

复制代码
delimiter $$
#delimiter开始和结束的语法,$$标志位,可以自定义不要用汉字,也不要数字开头,不能使用特殊字符开头
create procedure testl()
FBEGIN
select * from infol;
END SS
delimiter
#查看的两种方式
show procedure status where db='xy102';
show procedure status like '%test1%';#存储过程的名称
​
call test2 #按顺序执行,
存储过程怎么传参

IN 传入参数,调用者向存储过程传入值

out 输出参数 存储过程向调用者传出值,可以是多个值

复制代码
ssdelimiter $$
create procedure test4(out num int)
BEGINset 
num=100;
end $$
ssdelimiter;
call test4(@num)
select @num;
create table info2(id int(4));
insert into info2 value(@num);

INOUT 输入输出 既可以表示存储过程向调用者传出,也可以表示用户向存储

在存储过程中无需加@

复制代码
delimiter $$
 create procedure test3(inout high int)
BEGIN
   set high=(high+10);
end $$
delimiter;
​
call test2(@high);
​
set @high=185;
​
update info1 set high=@high where id = 2; 
控制语句
复制代码
REATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE,
    total_amount DECIMAL(10, 2)
);
​
#订单表
​
​
CREATE TABLE order_items (
    order_item_id INT PRIMARY KEY,
    order_id INT,
    product_id INT,
    quantity INT,
    price DECIMAL(10, 2)
);
#订单货表
​
INSERT INTO orders (order_id, customer_id, order_date, total_amount) VALUES
(1, 101, '2024-07-20', 0.00),
(2, 102, '2024-07-21', 0.00);
​
INSERT INTO order_items (order_item_id, order_id, product_id, quantity, price) VALUES
(1, 1, 1001, 2, 50.00),
(2, 1, 1002, 1, 30.00),
(3, 2, 1001, 1, 50.00),
(4, 2, 1003, 3, 20.00);
​
select sum(quantity * price)from order_items where order_id = 1;
select sum(quantity * price)from order_items where order_id = 2;
​
delimiter $$
 create procedure info1(inout price int)
BEGIN
   set price=(select sum(quantity * price)from order_items where order_id = 1);
end $$
delimiter;
select @price
call info1 (@price)
set @price=order_items
update info8 set total_amount=@price where id =1

1

相关推荐
转转技术团队几秒前
告别人工搬运!TiDB/MySQL双库同步工具如何为业务提效100%?
mysql·tidb·测试
快乐点吧22 分钟前
【MongoDB】windows安装、配置、启动
数据库·windows·mongodb
yangmf204024 分钟前
私有知识库 Coco AI 实战(二):摄入 MongoDB 数据
数据库·人工智能·mongodb·coco ai
努力进修29 分钟前
【金仓数据库征文】金仓数据库:开启未来技术脑洞,探索数据库无限可能
数据库·金仓数据库 2025 征文·数据库平替用金仓
键盘飞行员31 分钟前
使用 Node、Express 和 MongoDB 构建一个项目工程
数据库·mongodb·express
小白教程35 分钟前
MySQL主从数据库配置教程
数据库·mysql·adb·mysql8.0主从配置
foo1st1 小时前
MySQL 8(Ubuntu 18.04.6 LTS)安装笔记
笔记·mysql·ubuntu
CodeJourney.1 小时前
深度探索:DeepSeek赋能WPS图表绘制
数据库·人工智能·算法·信息可视化·excel
zru_96021 小时前
MongoDB 入门使用教程
数据库·mongodb
berryyan1 小时前
AKShare安装教程(一步一步适合新手)
数据库·投资