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

相关推荐
大模型玩家七七8 分钟前
安全对齐不是消灭风险,而是重新分配风险
android·java·数据库·人工智能·深度学习·安全
李少兄8 分钟前
MySQL 中为时间字段设置默认当前时间
android·数据库·mysql
码海踏浪17 分钟前
从简单到专业在OceanBase中查看SQL是否走索引
数据库·sql·oceanbase
qinyia18 分钟前
**使用AI助手在智慧运维中快速定位并修复服务异常:以Nginx配置错误导致502错误为例**
linux·运维·服务器·数据库·mysql·nginx·自动化
熊文豪24 分钟前
关系数据库替换用金仓——Oracle兼容性深度解析
数据库·oracle·金仓数据库·电科金仓·kes
eWidget30 分钟前
面向Oracle生态的国产高兼容数据库解决方案
数据库·oracle·kingbase·数据库平替用金仓·金仓数据库
A懿轩A33 分钟前
【MySQL 数据库】MySQL 数据库核心概念详解:库、表、字段、主键与关系型模型一文读懂
数据库·mysql·oracle
盒马coding37 分钟前
postgreSQL中调整Checkpoint的重要性
数据库·mysql·postgresql
怣501 小时前
MySQL多表连接完全指南:内连接与外连接(零基础入门版)
数据库·mysql
爱吃山竹的大肚肚1 小时前
文件上传大小超过服务器限制
java·数据库·spring boot·mysql·spring