Sql 简明教程
SQL - Stored Procedures
SQL Stored Procedures
SQL stored procedure 是一组预编译 SQL 语句(已准备好的 SQL 代码),只需在需要时调用即可重用该组语句。
An SQL stored procedure is a group of pre-compiled SQL statements (prepared SQL code) that can be reused by simply calling it whenever needed.
它可用于执行各种数据库操作,例如插入、更新或删除数据、生成报表和执行复杂计算。存储过程非常有用,因为它们允许你将一组 SQL 语句封装(捆绑)为单个单元,并使用不同的参数重复执行它们,从而可以轻松管理和重用代码。
It can be used to perform a wide range of database operations such as inserting, updating, or deleting data, generating reports, and performing complex calculations. Stored procedures are very useful because they allow you to encapsulate (bundle) a set of SQL statements as a single unit and execute them repeatedly with different parameters, making it easy to manage and reuse the code.
Syntax
创建 SQL 存储过程的基本语法如下:
The basic syntax to create an SQL stored procedure is as follows −
DELIMITER //
CREATE PROCEDURE procedure_name(parameter1 datatype, parameter2 datatype, ...)
BEGIN
-- SQL statements to be executed
END
DELIMITER ;
-
The CREATE PROCEDURE statement is used to create the procedure. We can define any number of input parameters as per the requirement.
-
The SQL statements that make up the procedure are placed between the BEGIN and END keywords.
Creating a Procedure
我们可以使用 SQL 中的 CREATE PROCEDURE 语句创建存储过程。以下是在创建存储过程的一些简单步骤:
We can create a stored procedure using the CREATE PROCEDURE statement in SQL. Following are the simple steps for creating a stored procedure −
-
Choose a name for the procedure.
-
Write the SQL code for the procedure.
-
We can then test the stored procedure by executing it with different input parameters.
Example
为了更好地理解它,让我们考虑一下 CUSTOMERS 表,其中包含客户的个人详细信息,包括他们的姓名、年龄、地址和工资等,如下所示:
To understand it better let us consider the CUSTOMERS table which contains the personal details of customers including their name, age, address and salary etc. as shown below −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
现在,使用如下所示的 INSERT 语句向此表中插入值:
Now, insert values into this table using the INSERT statement as follows −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(2, 'Khilan', 25, 'Delhi', 1500.00),
(3, 'Kaushik', 23, 'Kota', 2000.00),
(4, 'Chaitali', 25, 'Mumbai', 6500.00),
(5, 'Hardik', 27, 'Bhopal', 8500.00),
(6, 'Komal', 22, 'Hyderabad', 4500.00),
(7, 'Muffy', 24, 'Indore', 10000.00);
该表将被创建为:
The table will be created as −
ID |
NAME |
AGE |
ADDRESS |
SALARY |
1 |
Ramesh |
32 |
Ahmedabad |
2000.00 |
2 |
Khilan |
25 |
Delhi |
1500.00 |
3 |
Kaushik |
23 |
Kota |
2000.00 |
4 |
Chaitali |
25 |
Mumbai |
6500.00 |
5 |
Hardik |
27 |
Bhopal |
8500.00 |
6 |
Komal |
22 |
Hyderabad |
4500.00 |
7 |
Muffy |
24 |
Indore |
10000.00 |
现在,我们来看一个创建存储过程的简单示例,该存储过程接受一个输入参数并返回一个结果集。
Now, let us look at a simple example of creating a stored procedure that takes an input parameter and returns a result set.
在以下查询中,我们用 GetCustomerInfo 这个名称创建存储过程。然后给它提供一个称为 @CutomerAge 的单一输入参数。然后,存储过程从 CUSTOMERS 表中选择与输入参数匹配的 CutomerAge 值的所有记录。
In the following query, we are creating the stored procedure with the name GetCustomerInfo. then we provide it with a single input parameter called @CutomerAge. The stored procedure then selects all records from the CUSTOMERS table where the value of the CutomerAge matches the input parameter.
DELIMITER //
CREATE PROCEDURE GetCustomerInfo(IN CustomerAge INT)
BEGIN
SELECT * FROM CUSTOMERS WHERE AGE = CustomerAge;
END //
DELIMITER ;
Verification
我们可以使用 CALL 语句执行存储过程来测试它,如下所示 −
We can test the stored procedure by executing it using the CALL statement as shown below −
CALL GetCustomerInfo(25);
这将返回 CUSTOMERS 表中客户年龄为 25 时的所有列。
This will return all columns from the CUSTOMERS table where the customers age is 25.
ID |
NAME |
AGE |
ADDRESS |
SALARY |
2 |
Khilan |
25 |
Delhi |
1500.00 |
4 |
Chaitali |
25 |
Mumbai |
6500.00 |
Stored Procedure Parameter Types
数据库系统中的存储过程可以有不同类型的参数,而这些参数是要传递给存储过程在执行时使用的值的占位符。以下是在 SQL 中的存储过程参数的不同类型 −
Stored procedures in a database system can have different types of parameters, which are placeholders for values that will be passed to the stored procedure when it is executed. Following are the different types of stored procedure parameters in SQL −
S.No. |
Parameter & Description |
1 |
Input parameters These parameters are used to pass values from the calling statement to the stored procedure. |
2 |
Output parameters These parameters are used to return values from the stored procedure. |
3 |
Input/Output parameters These parameters allow a stored procedure to accept input values and return output values. |
Procedure with IN parameter
IN 是将接收输入值的该过程的默认参数。当调用存储过程时,我们可以将值作为参数传递。
IN is the default parameter of the procedure that will receive input values. We can pass the values as arguments when the stored procedure is being called.
这些值是只读的,所以它们不能由存储过程修改。
These values are read-only, so they cannot be modified by the stored procedure.
Example
在以下查询中,我们创建一个将客户 ID 作为输入参数并返回相应客户薪水的存储过程。
In the following query, we are creating a stored procedure that takes a customer ID as an input parameter and returns the corresponding customer salary.
过程体仅仅执行一个 SELECT 语句,从匹配输入参数的 CustomerID 的 CUSTOMERS 表中检索 Salary 列。
The procedure body simply performs a SELECT statement to retrieve the "Salary" column from the "CUSTOMERS" table, where the "CustomerID" matches the input parameter.
DELIMITER //
CREATE PROCEDURE GetCustomerSalary(IN CustomerID Int)
BEGIN
SELECT SALARY FROM CUSTOMERS WHERE ID = CustomerID;
END //
DELIMITER ;
Verification
我们可以执行它,使用不同的 ID 作为输入参数,如下面的查询所示 −
We can test it by executing it with different ID as an input parameter as shown in the query below −
CALL GetCustomerSalary(6);
这将返回 ID 为 6 的客户的工资,假设 CUSTOMERS 表中有相应的行 −
This will return the salary for the customer with an ID of 6, assuming there is a corresponding row in the CUSTOMERS table −
SALARY |
4500.00 |
Procedure with OUT parameter
OUT 参数用于从过程返回输出值。
The OUT parameter is used to return the output value from the procedure.
请注意,在使用 OUT 参数时,我们必须在将它传递到存储过程之前指定参数名称之前的 OUT 关键字。这告诉 SQL 数据库参数是一个输出参数,并且应该在存储过程中被赋予一个值。
Note that when using an OUT parameter, we must specify the keyword OUT before the parameter name when passing it to the stored procedure. This tells the SQL database that the parameter is an output parameter and should be assigned with a value in the stored procedure.
Example
在以下查询中,我们创建了用于统计具有相同年龄的客户的记录数的存储过程,并将此计数分配给包含记录数的 total 变量。
In the following query we are creating a stored procedure that used to count the number of records of customer having same age and assign this count to the 'total' variable which holds the number of records.
过程正文执行 SELECT 语句以获得来自“CUSTOMERS”表的具有相同年龄的记录计数
The procedure body performs a SELECT statement to get the count of records having same age from the "CUSTOMERS" table
DELIMITER //
CREATE PROCEDURE GetDetail(OUT total INT)
BEGIN
SELECT COUNT(AGE) INTO total FROM CUSTOMERS
WHERE AGE = 25;
END //
DELIMITER ;
调用已创建的过程并传递“total”参数
Calling the created procedure and passing the 'total' parameter
CALL GetDetail(@total);
此处,我们使用 SELECT 语句并获取计数 -
Here, we are using the SELECT statement and getting the count −
SELECT @total;
Procedure with INOUT parameter
INOUT 参数是 IN 参数和 OUT 参数的组合。你可以将数据传递到存储过程中并使用同一参数从存储过程中接收数据。
The INOUT parameter is a combination of an IN parameter and an OUT parameter. You can pass data into the stored procedure and receive data from the stored procedure using the same parameter.
要在存储过程中声明 INOUT 参数,我们需要在参数名前指定 INOUT 关键字。
To declare an INOUT parameter in a stored procedure, we need to specify the INOUT keyword before the parameter name.
Example
在以下查询中,我们为存储过程提供了两个 INOUT 参数: cust_id 和 curr_Salary 。这两个都用作输入和输出参数。
In the following query, we provide two INOUT parameters to the stored procedure: cust_id and curr_Salary. These two are used as both an input and output parameters.
存储过程首先使用 cust_id 参数从数据库中检索客户的当前薪水。然后将工资提高 10%,并使用相同的参数更新数据库中的客户工资。
The stored procedure first retrieves the current salary of the customer from the database using the cust_id parameter. It then increases the salary by 10% and updates the customers salary in the database using the same parameter.
DELIMITER //
CREATE PROCEDURE increaseSalary(INOUT Cust_Id Int, INOUT curr_Salary Int)
BEGIN
SELECT SALARY INTO curr_Salary From CUSTOMERS Where ID = Cust_Id;
SET curr_Salary = curr_Salary * 1.1;
Update CUSTOMERS SET SALARY = curr_Salary Where ID = Cust_Id;
END //
DELIMITER ;
Verification
我们可以通过使用不同的 ID 或输入参数来测试它,如下面的查询所示 -
We can test it by executing it with different ID or input parameters as shown in the query below −
SET @customerID = 1;
SET @salary = 0.0;
CALL increaseSalary(@customerID, @salary);
以下是查询以从存储过程选择更新后的工资
Following is Query to select the updated salary from the stored procedure
SELECT @salary AS updated_salary;
结果集获得如下 -
The result-set is obtained as −
updated_salary |
2200 |
Advantages of Stored Procedures
以下是存储过程的优点 -
Following are the advantages of stored procedures −
-
*Improved Performance: *Stored procedures are pre-compiled and stored on the server, so they can be executed more quickly than SQL statements that are sent from client applications.
-
*Code Reuse: *Stored procedures can be called from different client applications, which means that the same code can be reused across different applications. This reduces development time and maintenance costs.
-
*Reduced Network Traffic: *Because stored procedures are executed on the server, only the results are returned to the client, which reduces network traffic and improves application performance.
-
*Better Security: *Stored procedures can be used to enforce security rules and prevent unauthorized access to sensitive data. They can also limit the actions that can be performed by users, making it easier to maintain data integrity and consistency.
-
*Simplified Maintenance: * By storing SQL code in a single location, it becomes easier to maintain and update the code. This makes it easier to fix bugs, add new functionality, and optimize performance.
Drawbacks of Stored Procedures
以下是存储过程的缺点 -
Following are the disadvantages of stored procedures −
-
*Increased Overhead: *Stored procedures can consume more server resources than simple SQL statements, particularly when they are used frequently or for complex operations.
-
*Limited Portability: *Stored procedures are often specific to a particular database management system (DBMS), which means they may not be easily portable to other DBMSs.
-
*Debugging Challenges: *Debugging stored procedures can be more challenging than debugging simple SQL statements, particularly when there are multiple layers of code involved.
-
*Security Risks: *If stored procedures are not written correctly, they can pose a security risk, particularly if they are used to access sensitive data or to perform actions that could compromise the integrity of the database.