Stored procedures are reusable SQL code blocks in the database. The creation steps are: 1. Use DELIMITER to define the statement ending character; 2. Declare parameters and logic bodies through CREATE PROCEDURE; 3. Write operation statements between BEGIN...END. Use the CALL command when calling and pass parameters such as CALL calculate_bonus(5000, @bonus). Advantages include reduced network transmission, improved performance and maintenance. The applicable scenarios are high-frequency operations, performance optimization and complex data logic, while small projects are more suitable for direct splicing of SQL.
It is actually not difficult to write SQL stored procedures, but many people always feel a little confused at the beginning. Simply put, you can save a lot of duplicate code by just knowing how to define parameters, encapsulate logic, and then calling it correctly.

What is a stored procedure?
A stored procedure is a block of SQL code that can be used repeatedly, usually stored in a database. You can think of it as a "function", pass some parameters in it, and it will help you perform a series of operations. For example, batch update of data, processing complex queries, or performing data verification can all be used.

Compared with ordinary SQL statements, its advantages are:
- Reduce network transmission: the client only needs to call names and parameters, and does not need to send a large segment of SQL every time
- Improve performance: The database caches execution plans
- Easy to maintain: change once, all calls take effect
How to create a stored procedure?
The syntax of different databases is slightly different. Here I use MySQL as an example to illustrate the basic structure:

DELIMITER $$ CREATE PROCEDURE get_employee_salary(IN emp_id INT) BEGIN SELECT salary FROM employees WHERE id = emp_id; END$$ DELIMITER ;
There are several key points to pay attention to:
-
DELIMITER
is to prevent the semicolon from ending in advance. -
IN emp_id INT
means this is an input parameter -
BEGIN ... END
is the main part of the stored procedure
If it is an example with output parameters, for example, if you want to return a certain calculation result, you can write it like this:
CREATE PROCEDURE calculate_bonus(IN sales DECIMAL(10,2), OUT bonus DECIMAL(10,2)) BEGIN SET bonus = sales * 0.1; END$$
How to call stored procedures?
After creation, it can be used through CALL
. For example, the above example:
CALL calculate_bonus(5000, @bonus); SELECT @bonus;
You will find that the call method is simpler than when writing, especially when you have a lot of logic encapsulated inside, the call statements will hardly change.
If it is a process with multiple output parameters or complex logic, the calling method is similar, just a little more parameters.
Frequently asked questions include:
- Parameter type mismatch: for example, a string is passed in, and the process requires integers
- Forgot to declare variables: For example,
OUT
orINOUT
parameters were used, but@變量
reception was not used. - No permission to execute: You need to confirm that the user has permission to execute stored procedures
Tips: When should I use stored procedures?
- When you need to frequently perform a fixed set of SQL operations
- Need to reduce communication overhead between the application layer and the database
- The data logic is complicated, and I want to put control on the database side
Of course, not all scenarios are suitable for using stored procedures. For example, in small projects or lightweight services, it may be more flexible to spell SQL directly into the code. But if the business is stable and the performance requirements are high, the stored procedures are still worth writing.
Basically all this is it. If you write too much, you will find that the routines are almost the same. The key is to understand the parameter passing and calling methods.
The above is the detailed content of Creating and calling stored procedures in SQL.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OLTPisusedforreal-timetransactionprocessing,highconcurrency,anddataintegrity,whileOLAPisusedfordataanalysis,reporting,anddecision-making.1)UseOLTPforapplicationslikebankingsystems,e-commerceplatforms,andCRMsystemsthatrequirequickandaccuratetransactio

Toduplicateatable'sstructurewithoutcopyingitscontentsinSQL,use"CREATETABLEnew_tableLIKEoriginal_table;"forMySQLandPostgreSQL,or"CREATETABLEnew_tableASSELECT*FROMoriginal_tableWHERE1=2;"forOracle.1)Manuallyaddforeignkeyconstraintsp

To improve pattern matching techniques in SQL, the following best practices should be followed: 1. Avoid excessive use of wildcards, especially pre-wildcards, in LIKE or ILIKE, to improve query efficiency. 2. Use ILIKE to conduct case-insensitive searches to improve user experience, but pay attention to its performance impact. 3. Avoid using pattern matching when not needed, and give priority to using the = operator for exact matching. 4. Use regular expressions with caution, as they are powerful but may affect performance. 5. Consider indexes, schema specificity, testing and performance analysis, as well as alternative methods such as full-text search. These practices help to find a balance between flexibility and performance, optimizing SQL queries.

IF/ELSE logic is mainly implemented in SQL's SELECT statements. 1. The CASEWHEN structure can return different values ??according to the conditions, such as marking Low/Medium/High according to the salary interval; 2. MySQL provides the IF() function for simple choice of two to judge, such as whether the mark meets the bonus qualification; 3. CASE can combine Boolean expressions to process multiple condition combinations, such as judging the "high-salary and young" employee category; overall, CASE is more flexible and suitable for complex logic, while IF is suitable for simplified writing.

The method of obtaining the current date and time in SQL varies from database system. The common methods are as follows: 1. MySQL and MariaDB use NOW() or CURRENT_TIMESTAMP, which can be used to query, insert and set default values; 2. PostgreSQL uses NOW(), which can also use CURRENT_TIMESTAMP or type conversion to remove time zones; 3. SQLServer uses GETDATE() or SYSDATETIME(), which supports insert and default value settings; 4. Oracle uses SYSDATE or SYSTIMESTAMP, and pay attention to date format conversion. Mastering these functions allows you to flexibly process time correlations in different databases

The DISTINCT keyword is used in SQL to remove duplicate rows in query results. Its core function is to ensure that each row of data returned is unique and is suitable for obtaining a list of unique values ??for a single column or multiple columns, such as department, status or name. When using it, please note that DISTINCT acts on the entire row rather than a single column, and when used in combination with multiple columns, it returns a unique combination of all columns. The basic syntax is SELECTDISTINCTcolumn_nameFROMtable_name, which can be applied to single column or multiple column queries. Pay attention to its performance impact when using it, especially on large data sets that require sorting or hashing operations. Common misunderstandings include the mistaken belief that DISTINCT is only used for single columns and abused in scenarios where there is no need to deduplicate D

Create temporary tables in SQL for storing intermediate result sets. The basic method is to use the CREATETEMPORARYTABLE statement. There are differences in details in different database systems; 1. Basic syntax: Most databases use CREATETEMPORARYTABLEtemp_table (field definition), while SQLServer uses # to represent temporary tables; 2. Generate temporary tables from existing data: structures and data can be copied directly through CREATETEMPORARYTABLEAS or SELECTINTO; 3. Notes include the scope of action is limited to the current session, rename processing mechanism, performance overhead and behavior differences in transactions. At the same time, indexes can be added to temporary tables to optimize

The main difference between WHERE and HAVING is the filtering timing: 1. WHERE filters rows before grouping, acting on the original data, and cannot use the aggregate function; 2. HAVING filters the results after grouping, and acting on the aggregated data, and can use the aggregate function. For example, when using WHERE to screen high-paying employees in the query, then group statistics, and then use HAVING to screen departments with an average salary of more than 60,000, the order of the two cannot be changed. WHERE always executes first to ensure that only rows that meet the conditions participate in the grouping, and HAVING further filters the final output based on the grouping results.
