mysql的存储过程

xiaoxiao2021-02-28  90

一、定义

存储过程类似于函数,就是把一段代码封装起来,当要执行这一段代码的时候,可以通过调用该存储过程来实现。 在封装的语句体里面,可以用if/else,case,while 等控制结构,也可以进行sql编程

二、创建练习的表

create table articles ( id int unsigned auto_increment not null primary key NOT NULL PRIMARY KEY, title varchar(200), body text, fulltext (title,body) ) charset utf8; insert into articles (title,body) values ('MySQL Tutorial','DBMS stands for DataBase ...'), ('How To Use MySQL Well','After you went through a ...'), ('Optimizing MySQL','In this tutorial we will show ...'), ('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'), ('MySQL vs. YourSQL','In the following database comparison ...'), ('MySQL Security','When configured properly, MySQL ...');

三、介绍

1、创建存储过程语法

create procedure 存储过程名字 ([参数 [,...]]) [characteristic ...] routine_body

2、查看现有的存储过程

mysql> show procedure status;

3、删除存储过程

drop procedure 存储过程的名字;

4、调用存储过程

call 存储过程的名字([参数,...]);

四、存储过程实操

首先,在程序被定义的时候,用mysql客户端delimiter命令来把语句定界符从 ;变为$或者其他符号。这就允许用在程序体中的;定界符被传递到服务器而不是被mysql自己来解释。

1、第1个存储过程,体会”封装”sql

mysql> delimiter $ create procedure p1() begin select * from 表名; end$

2、第2个存储过程,体会”参数”

create procedure p2(num int) begin select * from 表名 where id > num; end$

3、第3个存储过程,体会”控制结构”

create procedure p3(num int,j char(1)) begin if j='h' then select * from 表名 where id > num; else select * from 表名 where id < num; end if; end$

4、第4个存储过程,计算1–>n的和

create procedure p4(num smallint) begin declare i int; declare s int; set i = 1; set s = 0; while i <= num do set s = s + i; set i = i + 1; end while; select s; end$

转载请注明原文地址: https://www.6miu.com/read-40765.html

最新回复(0)