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

相关推荐
徐子元竟然被占了!!7 小时前
Linux-systemctl
linux·数据库·oracle
YJlio9 小时前
Active Directory 工具学习笔记(10.8):AdInsight——保存与导出(证据留存、共享与二次分析)
数据库·笔记·学习
suoyue_zhan9 小时前
GBase的管理监控平台GEM实践指南
数据库
哈哈老师啊9 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
小小8程序员9 小时前
Redis-10
数据库·redis·缓存
liuzhilongDBA9 小时前
从collation mismatch异常到其原理
数据库·version·glibc·postgres·collation
梁萌9 小时前
MySQL数据库分库分表介绍
数据库·mysql·shardingsphere·分库分表
占疏11 小时前
dify API访问工作流/聊天
开发语言·数据库·python
Cat God 00712 小时前
SQL使用及注意事项
数据库·sql·mysql