SQL must know - using stored procedures

"SQL must know must know" reading notes

1. Stored procedure

A stored procedure is a collection of SQL statements and flow control statements. A stored procedure is a set of SQL statements to complete a specific function, which is stored in the database after the first compilation, and does not need to be compiled again when called again. The user executes the stored procedure by specifying its name and giving parameters (if the stored procedure has parameters).

Stored procedures contain logical control statements and data manipulation statements, which can accept parameters, output parameters, return single or multiple data sets, and return values.

2. Why use stored procedures

Reasons to use stored procedures:

  • Complex operations can be simplified by encapsulating processing in an easy-to-use unit.
  • Consistency of the data is guaranteed because there is no requirement to repeatedly establish a series of processing steps. If all developers and applications use the same stored procedure, the code used is the same. (An extension of this is error prevention. The more steps that need to be performed, the greater the chance of error. Error prevention guarantees data consistency.)
  • Simplify change management. If the table names, column names, or business logic (or whatever) changes, then just change the code of the stored procedure. People using it don't even need to know about the changes. (An extension of this is security. Restricting access to underlying data through stored procedures reduces the chance of data corruption [unintentional or otherwise]).
  • Because stored procedures are usually stored in compiled form, the DBMS does less work to process commands, improving performance.
  • There are some SQL elements and features that can only be used in a single request, and stored procedures can use them to write more functional and flexible code.

In other words, there are three main benefits to using stored procedures, namely simplicity, security, and high performance.

Disadvantages of stored procedures:

  • Stored procedure statements differ in different DBMSs.
  • Generally speaking, writing stored procedures is more complex than writing basic SQL statements, requiring higher skills and more experience.

3. Execute the stored procedure

EXECUTE accepts the stored procedure name and any parameters that need to be passed to it.

EXECUTE AddNewProduct(
        'JTS01',
        'Stuffed Eiffel Tower',
        6.49,
        'Plush stuffed toy with the text La Tour Eiffel in red white and blue'
);

This executes a stored procedure called AddNewProduct to add a new product to the Products table. AddNewProduct consists of four parameters, namely: vendor ID (the primary key of the Vendors table), product name, price and description. These 4 parameters match the 4 expected variables in the stored procedure (the part that defines the stored procedure itself).

We notice that in the Products table there is another required value column prod_id column, which is the primary key of this table. Why is this value not passed to the stored procedure as a property? To ensure that this ID is properly generated, it is best to automate the process of generating this ID (rather than relying on end-user input).

The above is the basic form of stored procedure execution. For a specific DBMS, the following implementation choices may be included:

  • The parameter is optional and has a default value when no parameter is provided;
  • Parameters are given out of order, and parameter values ​​are given in the form of "parameter=value".
  • Output parameters, which allow the stored procedure to update the parameters used in the executing application.
  • Retrieve data with a SELECT statement.
  • Return code that allows the stored procedure to return a value to the executing application.

4. Create a stored procedure

The following example counts customers with email addresses in the mailing list.

CREATE PRODUCT MailingListCount(
    ListCount OUT INTEGER
)
IS
v_rows INTEGER;
BEGIN 
    SELECT COUNT(*) INTO v_rows
    FROM Customers
    WHERE NOT cust_email IS NULL;
    ListCount := v_rows;
END;

This stored procedure has a parameter called ListCount. This parameter returns a value from the stored procedure rather than passing a value to the stored procedure. The keyword OUT is used to indicate this behavior. Oracle supports IN (passing a value to a stored procedure), OUT (returning a value from a stored procedure, as here), and INOUT (passing a value to a stored procedure and returning a value from a stored procedure) type parameters. The code for the stored procedure is enclosed in BEGIN and END statements, where a simple SELECT statement is executed that retrieves customers with email addresses. Then set the ListCount (the output parameter to be passed) with the number of rows to retrieve.

The calling process can be as follows:

var ReturnValue NUMBER
EXEC MailingListCount(:ReturnValue);
SELECT ReturnValue;

This code declares a variable to hold any value returned by the stored procedure, executes the stored procedure, and uses a SELECT statement to display the returned value.

Here is another example, this time inserting a new order in the Orders table. This procedure is for SQL Server only, but it illustrates some of the uses and techniques of stored procedures:

CREATE PROCEDURE NewOrder @cust_id CHAR(10)
AS
-- Declare variable for older number
DECLARE @order_num INTRGER
-- Get current highest order number
SELECT @order_num = MAX(order_num)
-- Determine next order number
SELECT @order_num = @order_num + 1
-- Insert new order
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(@order_num,GETDATE(),@cust_id)
-- Return order number
RETURN @order_num;

This stored procedure creates a new order in the Orders table. It has only one parameter, the ID of the customer who placed the order. The columns order number and order date are automatically generated in the stored procedure. The code first declares a local variable to store the order number. Next, retrieve the current maximum order number (using the MAX() function) and increment it by 1 (using the SELECT statement). Then use an INSERT statement to insert an order consisting of the newly generated order number, the current system date (retrieved with the GETDATE() function), and the passed customer ID. Finally, use RETUN @order_num to return the order number (required for processing order items). Note that this code is commented and should be multiple when writing stored procedures.

Note:
Reference article: https://blog.csdn.net/tojohnonly/article/details/70738629

-- 创建应该存储过程
create procedure GetUsers()
begin
    select * from user;
end;

-- 调用存储过程
call Getusers();

-- 输出存储过程
drop procedure if exists Getusers;

Stored procedure with parameters:

Example 1:

create procedure GetScores(
    out minScore decimal(8,2),
    out avgScore decimal(8,2),
    out maxScore decimal(8,2)
)

begin
    select min(score) into minScore from user;
    select avg(score) into avgScore from user;
    select max(score) into maxScore from user;
end;

To call this stored procedure, 3 variables must be specified (all MySql variables must start with @) as follows:

call GetUsers(@minScore,@avgScore,@maxScore);

The call does not have any output, just assign the result of the call to the variables @minScore, @avgScore, @maxScore passed in when calling, and then call to display the value of the variable:

select @minScore,@avgScore,@maxScore;

Example 2:

Using the IN parameter, enter a user id and return the user's name:

create procedure GetNameById(
    in userID int,
    out userName varchar(200)
)

begin
    select name from user
    where id = userID
    into userName;
end;

Call the stored procedure:

call GetNameByID(1,@userName);
select @userName;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854918&siteId=291194637