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

相关推荐
!chen1 分钟前
【Spring Boot】自定义starter
java·数据库·spring boot
流烟默13 分钟前
MySQL索引调优之索引顺序必须和字段顺序一致吗?
mysql·索引调优
十碗饭吃不饱39 分钟前
sql报错:java.sql.SQLSyntaxErrorException: Unknown column ‘as0‘ in ‘where clause‘
java·数据库·sql
我是Superman丶1 小时前
【优化】Mysql指定索引查询或忽略某个索引
数据库·mysql
程序定小飞1 小时前
基于springboot的在线商城系统设计与开发
java·数据库·vue.js·spring boot·后端
呆呆小金人1 小时前
SQL入门: HAVING用法全解析
大数据·数据库·数据仓库·sql·数据库开发·etl·etl工程师
LL_break2 小时前
Mysql数据库
java·数据库·mysql
野犬寒鸦2 小时前
从零起步学习Redis || 第十一章:主从切换时的哨兵机制如何实现及项目实战
java·服务器·数据库·redis·后端·缓存
倔强的石头_2 小时前
面向大数据架构的演进:为何 Apache IoTDB 是与生态无缝融合的理想之选?
数据库
Elastic 中国社区官方博客3 小时前
如何减少 Elasticsearch 集群中的分片数量
大数据·数据库·elasticsearch·搜索引擎·全文检索