Table of Contents
1. 目标
2. 语法
3. 说明
4. 示例
5. 调用存储过程
6. 查看存储过程
Home Database Mysql Tutorial MySQL存储过程使用_MySQL

MySQL存储过程使用_MySQL

Jun 01, 2016 pm 01:02 PM
process

1. 目标

掌握如何创建存储过程

2. 语法

CREATE PROCEDURE sp_name([proc_parameter])

[characteristics...] routine_body

3. 说明

CREATE PROCEDURE为用来创建存储过程的关键字; sp_name为存储过程的名称; proc_parameter为指定存储过程的参数列表,参数列表的形式:[IN | OUT | INOUT] param_name type
IN:表示输入参数,OUT:表示输出参数,INOUT:表示既可以输入也可以输出;param_name表示参数的名称;type表示参数的类型,该类型可以是MySQL数据库中的任意类型。
characteristics指定存储过程的特性,可以有以下几种取值方式:
LANGUAGE SQL: 说明routine_body部分由SQL语句组成,当前系统支持的语言为SQL, SQL是LANGUAGE特性的唯一值;[NOT] DETERMINISTIC: 指明存储过程执行的结果是否正确。DETERMINISTIC表示结果是确定的。每次执行存储过程时,相同的输入会得到相同的输出;而NOT DETERMINISTIC表示结果是不确定的,相同的输入可能得到不同的输入。如果没有指定任意一个值,默认为NOT DETERMINISTIC。{CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA}: 指明子程序使用SQL语句限制。CONTAINS SQL表明子程序包含SQL语句,但是不包含读写数据的语句;NO SQL表明子程序不包含SQL语句;READS SQL DATA说明子程序包含读写数据的语句;MODIFIES SQL DATA表明子程序包含写数据的语句;默认情况下,系统会指定为CONTAINS SQL;SQL SECURITY { DEFINER|INVOKER}: 指明谁有权限来执行。DEFINER表示只有定义存储过程者才能执行;INVOKER表示拥有权限的调用者可以执行。默认情况下,系统指定为DEFINER。COMMENT 'string': 注释信息,可以用来描述存储过程或者函数。
routine_body是SQL代码内容,可以用BEGIN...END来表示SQL代码的开始与结束。

4. 示例

1) 创建示例数据库

create database hr;
use hr;
Copy after login
2) 创建示例用到的表并插入样例数据
create table employees
(
	employee_id int(11) primary key not null auto_increment,
	employee_name varchar(50) not null,
	employee_sex varchar(10) default '男',
	hire_date datetime not null default current_timestamp,
	employee_mgr int(11),
	employee_salary float default 3000,
	department_id int(11)
);
Copy after login
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('David Tian','男',10,7500,1);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Black Xie','男',10,6600,1);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Moses Wang','男',10,4300,1);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Rena Ruan','女',10,5300,1);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Sunshine Ma','女',10,6500,2);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Scott Gao','男',10,9500,2);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Warren Si','男',10,7800,2);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Kaishen Yang','男',10,9500,3);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Simon Song','男',10,5500,3);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Brown Guan','男',10,5000,3);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Eleven Chen','女',10,3500,2);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Cherry Zhou','女',10,5500,4);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Klause He','男',10,4500,5);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Maven Ma','男',10,4500,6);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Stephani Wang','女',10,5500,7);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Jerry Guo','男',10,8500,1);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Gerardo Garza','男',10,25000,8);
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Derek Wu','男',10,5500,5);
Copy after login
3) 查看插入的样例数据
select * from employees;
Copy after login

\

4) 创建计算平均工资的存储过程

DELIMITER //
create procedure calculate_emp_sal_avg_p()
begin
	select AVG(employee_salary) as average_salary
	from employees;
end//
DELIMITER ;
Copy after login

说明

DELIMETER //:该语句作用是将MySQL的结果结束符设置为//,因为MySQL默认的语句结束符为分号";",为了避免与存储过程中SQL语句的结束符相冲突,需要使用DELIMETER改变存储过程的结束符,并以"END //" 结束存储过程。存储过程定义完毕以后再使用"DELIMETER ; "恢复默认结束符。DELIMETER也可以指定其它符号为结束符。

5. 调用存储过程

存储过程是通过CALL语句进行调用的,语法如下:

CALL sp_name([parameter[,...]])

CALL语句调用一个先前用CREATE PROCEDURE创建的存储过程,其中sp_name为存储过程名称,parameter为存储过程参数。

CALL calculate_emp_sal_avg_p();
Copy after login
\

6. 查看存储过程

1) SHOW STATUS 语句查看存储过程

语法

SHOW PROCEDURE STATUS [LIKE 'pattern']

这个语句是一个MySQL的扩展,它返回子程序的特征,如数据库、名字、类型、创建者及创建日期和修改日期。

LIKE语句表示匹配存储过程的名称;

\

2) SHOW CREATE 语句查看存储过程定义

语法

SHOW CREATE PROCEDURE sp_name

这个语句是一个MySQL的扩展,类似于SHOW CREATE TABLE,它返回一个可用来重新创建已命名存储过程的确切字符串。

\

3) 从information_schema.Routines表中查看存储过程

语法

SELECT * FROM information_schema.Routines WHERE ROUTINE_NAME='sp_name';

ROUTINE_NAME字段中存储的是存储过程或者函数的名称;sp_name指存储过程或函数名称;

\

如果您们在尝试的过程中遇到什么问题或者我的代码有错误的地方,请给予指正,非常感谢!

联系方式:david.louis.tian@outlook.com

版权@:转载请标明出处!
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

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.

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.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

See all articles