Home Database Mysql Tutorial [MySQL 08] Stored procedure

[MySQL 08] Stored procedure

Feb 04, 2017 pm 01:17 PM

First of all, for SQL stored procedures, it is similar to the definition method and calling method in Java.

1. Create a stored procedure

In MySQL, the basic form of a stored procedure:

CREATE PROCEDURE sp_name ([proc_parameter[,...]])  
        [characteristic ...] routine_body
Copy after login
  • The sp_name parameter is the name of the stored procedure;

  • proc_parameter represents the parameter list of the stored procedure;

  • characteristic parameter specifies the characteristics of the stored procedure;

  • routine_body The parameter is the content of the SQL code. You can use BEGIN...END to mark the beginning and end of the SQL code.

  • Each parameter in proc_parameter consists of 3 parts. These three parts are input and output types, parameter names and parameter types. Its form is as follows:

[ IN | OUT | INOUT ] param_name type
Copy after login
  • IN represents input parameters;

  • OUT represents output parameters;

  • INOUT means it can be either input or output;

  • The param_name parameter is the parameter name of the stored procedure;

  • The type parameter specifies the parameter type of the stored procedure, which can be any data type of the MySQL database

Simplified definition:

create procedure 过程名(参数...)
begin
    SQL语句...end
Copy after login

Call:

call 过程名(实参)
Copy after login

Note:
Before defining, you need to change the default statement end ';' to something else, such as '&&', so that the semicolon defined in the stored procedure will not be regarded as the end of the statement ( Otherwise it will be submitted directly). After defining it, you need to restore ';' to the default terminator.

2. Stored procedures without parameters

//建立存储过程mysql> delimiter %%
mysql> create procedure p1()    
-> begin    
-> select Sname,Ssex from student;    
-> end %%mysql> delimiter ;  
//调用存储过程mysql> call p1(); 
+--------+------+| Sname  | Ssex |
+--------+------+| 赵英    | 女   |
| 郑美丽  | 女   |
| 李哲    | 男   |
| 王洋    | 女   |
| 王平    | 男   |
| 赵东新  | 男   |
| 王新    | 男   |
| 陶丽平  | 男   |
| 陈文    | 女   |
| 蔡天    | 女   || 杨洋    | 男   |
+--------+------+
Copy after login

3. Stored procedures with parameters

//查询mysql> select * from employee;
+------------+------------+------------+--------------+| employeeID | name       | job        | departmentID |
+------------+------------+------------+--------------+| 6651       | Ajay Patel | Programmer |          128 |
| 7513       | Nora Edwar | Programmer |          128 |
| 9006       | Candy Burn | Systems Ad |          128 |
| 9842       | Ben Smith  | DBA        |           42 |
| 9843       | Pert Park  | DBA        |           42 |
| 9845       | Ben Patel  | DBA        |          128 |
| 9846       | Red Right  | NULL       |          128 |
| 9847       | Run Wild   | NULL       |          128 |
| 9848       | Rip This J | NULL       |          128 |
| 9849       | Rip This J | NULL       |          128 |
| 9850       | Reader U   | NULL       |          128 || 6651       | Ajay Patel | Programmer |          128 |
+------------+------------+------------+--------------+//建立存储过程mysql> delimiter &&
mysql> create procedure p4(in employeeID char(4),in name varchar(20),in job varchar(20),in departmentID int(11))    -> begin    
-> insert into employee value(employeeID,name,job,departmentID);    -> select * from employee;    -> end &&mysql> delimiter ;  
//调用存储过程mysql> call p4('7322','cid','udewhuuwdwq',127);
+------------+------------+-------------+--------------+| employeeID | name       | job         | departmentID |
+------------+------------+-------------+--------------+| 6651       | Ajay Patel | Programmer  |          128 |
| 7513       | Nora Edwar | Programmer  |          128 |
| 9006       | Candy Burn | Systems Ad  |          128 |
| 9842       | Ben Smith  | DBA         |           42 |
| 9843       | Pert Park  | DBA         |           42 |
| 9845       | Ben Patel  | DBA         |          128 |
| 9846       | Red Right  | NULL        |          128 |
| 9847       | Run Wild   | NULL        |          128 |
| 9848       | Rip This J | NULL        |          128 |
| 9849       | Rip This J | NULL        |          128 |
| 9850       | Reader U   | NULL        |          128 |
| 6651       | Ajay Patel | Programmer  |          128 || 7322       | cid        | udewhuuwdwq |          127 |
+------------+------------+-------------+--------------+
Copy after login

4. Stored procedures with return values ​​

//建立存储过程mysql> delimiter &&
mysql> create procedure p9(in employeeID char(4),in name varchar(20),in job varchar(20),in departmentID int(11),out num int)
    -> begin
    -> insert into employee value(employeeID,name,job,departmentID);
    -> select count(*) into num from employee;
    -> end &&

mysql> delimiter ; 

//调用存储过程mysql> call p9('3632','dueh','xianggang',28,@num);//注意输出变量的输出mysql> select @num;
+------+
| @num |
+------+
|   15 |
+------+//////////////////////////系统变量名称:@@变量名/// //用户变量名称:@变量名 ///
Copy after login


5. Use of variables

In stored procedures and functions, variables can be defined and used. Users can use the DECLARE keyword to define variables. The variable can then be assigned a value. The scope of these variables is in the BEGIN...END program section. This section will explain how to define variables and assign values ​​to variables.

1. Defining variables

You can use the DECLARE keyword to define variables in MySQL. The basic syntax for defining variables is as follows:

DECLARE var_name[,...] type [DEFAULT value]
Copy after login

Among them, the DECLARE keyword is used to declare variables; the var_name parameter is the name of the variable, where multiple variables can be defined at the same time; the type parameter is used to specify the type of the variable; The DEFAULT value clause sets the default value of the variable to value. When the DEFAULT clause is not used, the default value is NULL.

DECLARE  my_sql  INT  DEFAULT 10 ; //定义变量my_sql,数据类型为INT型,默认值为10
Copy after login

2. Assigning values ​​to variables

You can use the SET keyword in MySQL to assign values ​​to variables. The basic syntax of the SET statement is as follows:

SET var_name = expr[,var_name = expr] ...
Copy after login

Among them, the SET keyword is used to assign values ​​to variables; the var_name parameter is the name of the variable; the expr parameter is the assignment expression. A SET statement can assign values ​​to multiple variables at the same time. The assignment statements for each variable are separated by commas.

SET my_sql = 30 ; //为变量my_sql赋值为30
Copy after login

You can also use the SELECT...INTO statement to assign values ​​to variables in MySQL. The basic syntax is as follows:

SELECT col_name[,…] INTO var_name[,…]
FROM table_name WEHRE condition
Among them, the col_name parameter represents the query field name; the var_name parameter is the name of the variable; The table_name parameter refers to the name of the table; the condition parameter refers to the query condition.

SELECT d_id INTO my_sql  
   FROM employee WEHRE id=2 ; //从employee表中查询id为2的记录,将该记录的d_id值赋给变量my_sql
Copy after login

6. Define conditions and handlers

Defining conditions and handlers is to define in advance the problems that may be encountered during program execution. And solutions to these problems can be defined in the handler. This approach can predict possible problems in advance and propose solutions. This can enhance the program's ability to handle problems and prevent the program from stopping abnormally. In MySQL, conditions and handlers are defined through the DECLARE keyword. This section explains in detail how to define conditions and handlers.

1. Define conditions

The DECLARE keyword can be used in MySQL to define conditions. Its basic syntax is as follows:

DECLARE  condition_name  CONDITION  FOR  condition_value  
condition_value:  
      SQLSTATE [VALUE] sqlstate_value | mysql_error_code
Copy after login

其中,condition_name参数表示条件的名称;condition_value参数表示条件的类型;sqlstate_value参数和mysql_error_code参数都可以表示MySQL的错误。例如ERROR 1146 (42S02)中,sqlstate_value值是42S02,mysql_error_code值是1146。

//定义"ERROR 1146 (42S02)"这个错误,名称为can_not_find
//方法一:使用sqlstate_value  DECLARE  can_not_find  CONDITION  FOR  SQLSTATE  '42S02' ;  
//方法二:使用mysql_error_code  DECLARE  can_not_find  CONDITION  FOR  1146 ;
Copy after login

2.定义处理程序

MySQL中可以使用DECLARE关键字来定义处理程序。其基本语法如下:

DECLARE handler_type HANDLER FOR 
condition_value[,...] sp_statement  
handler_type:  
    CONTINUE | EXIT | UNDO  
condition_value:  
    SQLSTATE [VALUE] sqlstate_value |
condition_name  | SQLWARNING  
       | NOT FOUND  | SQLEXCEPTION  | mysql_error_code
Copy after login
  • handler_type参数指明错误的处理方式,该参数有3个取值。这3个取值分别是CONTINUE、EXIT和UNDO。

  • CONTINUE表示遇到错误不进行处理,继续向下执行; EXIT表示遇到错误后马上退出;

  • UNDO表示遇到错误后撤回之前的操作,MySQL中暂时还不支持这种处理方式

注意:通常情况下,执行过程中遇到错误应该立刻停止执行下面的语句,并且撤回前面的操作。但是,MySQL中现在还不能支持UNDO操作。因此,遇到错误时最好执行EXIT操作。如果事先能够预测错误类型,并且进行相应的处理,那么可以执行CONTINUE操作。

condition_value参数指明错误类型,该参数有6个取值。sqlstate_value和mysql_error_code与条件定义中的是同一个意思。condition_name是DECLARE定义的条件名称。SQLWARNING表示所有以01开头的sqlstate_value值。NOT FOUND表示所有以02开头的sqlstate_value值。SQLEXCEPTION表示所有没有被SQLWARNING或NOT FOUND捕获的sqlstate_value值。sp_statement表示一些存储过程或函数的执行语句。

//定义处理程序的几种方式
//方法一:捕获sqlstate_value  
DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02'SET @info='CAN NOT FIND';  
//方法二:捕获mysql_error_code  
DECLARE CONTINUE HANDLER FOR 1146 SET @info='CAN NOT FIND';  
//方法三:先定义条件,然后调用  
DECLARE  can_not_find  CONDITION  FOR  1146 ;  
DECLARE CONTINUE HANDLER FOR can_not_find SET 
@info='CAN NOT FIND';  
//方法四:使用SQLWARNING  
DECLARE EXIT HANDLER FOR SQLWARNING SET @info='ERROR';  
//方法五:使用NOT FOUND  
DECLARE EXIT HANDLER FOR NOT FOUND SET @info='CAN NOT FIND';  
//方法六:使用SQLEXCEPTION  
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @info='ERROR';
Copy after login
  • 第一种方法是捕获sqlstate_value值。如果遇到sqlstate_value值为42S02,执行CONTINUE操作,并且输出”CANNOT FIND”信息。

  • 第二种方法是捕获mysql_error_code值。如果遇到mysql_error_code值为1146,执行CONTINUE操作,并且输出”CAN NOT FIND”信息。

  • 第三种方法是先定义条件,然后再调用条件。这里先定义can_not_find条件,遇到1146错误就执行CONTINUE操作。

  • 第四种方法是使用SQLWARNING。SQLWARNING捕获所有以01开头的sqlstate_value值,然后执行EXIT操作,并且输出”ERROR”信息。

  • 第五种方法是使用NOT FOUND。NOT FOUND捕获所有以02开头的sqlstate_value值,然后执行EXIT操作,并且输出”CAN NOT FIND”信息。

  • 第六种方法是使用SQLEXCEPTION。SQLEXCEPTION捕获所有没有被SQLWARNING或NOT FOUND捕获的sqlstate_value值,然后执行EXIT操作,并且输出”ERROR”信息。

以上就是 【MySQL 08】存储过程的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to recover data after SQL deletes rows How to recover data after SQL deletes rows Apr 09, 2025 pm 12:21 PM

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

See all articles