Home Database Mysql Tutorial mysql stored procedure stored function

mysql stored procedure stored function

May 18, 2023 am 10:46 AM

MySQL is a popular relational database management system that supports the creation and use of database objects such as stored procedures and stored functions. In this article, we will dive into the concepts, uses, syntax, and examples of MySQL stored procedures and stored functions.

1. What are stored procedures and stored functions?

Stored procedures and stored functions are two types of database objects in MySQL. They can all be created on the MySQL server side and can be called and executed by other client programs. What they have in common is that they can encapsulate a series of SQL statements and implement some complex database operations or business logic.

Stored Procedure (Stored Procedure) is a set of predefined SQL statements, similar to subroutines or functions in other programming languages. They are written as a single SQL statement and stored on the server, and can be called when needed. Stored procedures can be used to implement some specific business requirements, such as batch processing of data, execution of transactions, fast query, etc. Stored procedures can accept parameters when executed and can also return results after execution.

A stored function (Stored Function) is a procedure that can be called in a SQL query, which accepts input parameters and returns a single value. Similar to stored procedures, stored functions are also a collection of SQL statements. Stored functions are typically used to calculate, convert, or manipulate values ​​and return the results to the caller. Unlike stored procedures, stored functions can only return a single value and cannot return a set of results. Stored functions are widely used in queries and reports.

2. Advantages of stored procedures and stored functions

  1. Improve database performance: stored procedures and stored functions can run on the server, reducing the load of data transmission and network communication overhead , thereby improving database performance.
  2. Better security: Stored procedures and stored functions can rely on access control to control access to tables. Because the SQL codes are stored in the database server, users cannot access them directly and can only use them with specific permissions.
  3. Simplify the code: Stored procedures and stored functions can reuse SQL code, reducing repeated SQL queries and logic code writing, reducing the amount of code and making it more maintainable.
  4. Portability: Stored procedures and stored functions can be reused in different applications and portable between different operating systems and database platforms.

3. Create and use stored procedures

  1. Create stored procedures:

The syntax for creating stored procedures is as follows:

CREATE PROCEDURE procedure_name ([IN | OUT | INOUT] parameter datatype [, …])
BEGIN
SQL statements;
END;
Copy after login
  • procedure_name: The name of the stored procedure
  • parameter: The parameter of the stored procedure, which can be an IN (default) input parameter, an OUT output parameter and an INOUT (simultaneous input and output) parameter.
  • datatype: the data type of the parameter
  • SQL statements: the main statement of the stored procedure

For example, the following stored procedure will pass in the amount and customer ID, and Add the amount to the customer account balance:

CREATE PROCEDURE add_amount(IN amt INT, IN cust_id INT)
BEGIN
UPDATE customers SET balance = balance + amt WHERE id = cust_id;
END;
Copy after login
  1. Call the stored procedure:

The syntax for calling the stored procedure is as follows:

CALL procedure_name([parameter_value]);
Copy after login

For example, the following code The add_amount() stored procedure just created will be called:

CALL add_amount(100, 1);
Copy after login

The above code will increase the balance of the customer with ID 1 by 100 yuan in the customers table.

4. Create and use stored functions

  1. Create a stored function:

The syntax for creating a stored function is as follows:

CREATE FUNCTION function_name ([parameter datatype [, …]])
RETURNS datatype
BEGIN
SQL statements;
RETURN return_value;
END;
Copy after login
  • function_name: the name of the stored function
  • parameter: the parameter of the stored function
  • datatype: the data type of the parameter
  • SQL statements: the main statement of the stored function
  • return_value: The return value of the stored function

For example, the following example creates a stored function for calculating the average:

CREATE FUNCTION average (a INT, b INT)
RETURNS INT
BEGIN
DECLARE result INT;
SET result = (a + b) / 2;
RETURN result;
END;
Copy after login
  1. Calling the stored function:

The syntax for calling a stored function is similar to calling a stored procedure:

SELECT function_name([parameter_value]);
Copy after login

For example, the following code will call the average() stored function just created:

SELECT average(10, 20);
Copy after login

The above code will Returns 15, which is the result of (10 20)/2.

5. Examples of stored procedures and stored functions

  1. Examples of stored procedures

The following stored procedure will automatically calculate the average age of all customers, and put the results into another table:

CREATE PROCEDURE calc_avg_age()
BEGIN
DECLARE avg_age FLOAT;
SELECT AVG(YEAR(CURDATE()) - YEAR(birth_date)) INTO avg_age FROM customers;
INSERT INTO statistics (name, value) VALUES ('avg_age', avg_age);
END;
Copy after login
  1. Example of stored function

The following stored function will return the number of days between two dates:

CREATE FUNCTION days_between (date1 DATE, date2 DATE)
RETURNS INT
BEGIN
DECLARE num_days INT;
SET num_days = DATEDIFF(date2, date1);
RETURN num_days;
END;
Copy after login

Now, I want to know the number of days between Christmas and New Year 2022, we can use the following code to call the above stored function:

SELECT days_between('2022-12-25', '2023-01-01');
Copy after login

The above code will return 7, which is between the two dates number of days.

6. Conclusion

So far, we have understood the concepts, syntax and examples of MySQL stored procedures and stored functions. These objects can help us better organize SQL code and improve database performance and maintainability. In practical applications, stored procedures and stored functions are widely used in data warehouses, business intelligence, applications and other fields. However, be careful not to overuse them, as this may reduce the readability and maintainability of your code.

The above is the detailed content of mysql stored procedure stored function. For more information, please follow other related articles on the PHP Chinese website!

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)

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.

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

Difference between clustered index and non-clustered index (secondary index) in InnoDB. Difference between clustered index and non-clustered index (secondary index) in InnoDB. Apr 02, 2025 pm 06:25 PM

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values ​​and pointers to data rows, and is suitable for non-primary key column queries.

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.

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Can mysql and mariadb coexist Can mysql and mariadb coexist Apr 08, 2025 pm 02:27 PM

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Apr 02, 2025 pm 07:05 PM

MySQL supports four index types: B-Tree, Hash, Full-text, and Spatial. 1.B-Tree index is suitable for equal value search, range query and sorting. 2. Hash index is suitable for equal value searches, but does not support range query and sorting. 3. Full-text index is used for full-text search and is suitable for processing large amounts of text data. 4. Spatial index is used for geospatial data query and is suitable for GIS applications.

See all articles