[SQL Must Know and Know] - Lesson 19 Using Stored Procedures

Table of contents

written in front

19.1 Stored procedures

19.2 Why use stored procedures

19.3 Executing stored procedures

19.4 Creating stored procedures

        comment code


        This lesson describes what stored procedures are, why they are used, how they are used, and the basic syntax for creating and using stored procedures.

written in front

        The content of this lesson is mainly about [stored process], which is often called procedure. In actual work, many domestic companies will deliberately avoid this method (at least the companies I know in Beijing, Shanghai, Hangzhou, etc.) , and the content of this lesson is also extremely boring. I haven't introduced the grammar of the procedure, which can be said to be very complicated and not so easy to understand.

        If you know several languages ​​at the same time, then you must have felt it. There are subtle differences between different languages, even a function, each language has a different implementation method/name, and the mixing of languages ​​will make your subsequent work difficult. / Learning is getting harder.

        Suggestions are not required for work, this lesson can be skipped, or just for understanding. If you need an in-depth understanding, this course cannot meet your needs, and you need to find a more suitable blog/course.

19.1 Stored procedures

        Most of the SQL statements we've used so far have been single statements against one or more tables. Not all operations are so simple, and often some complex operations require multiple statements to complete.

        In simple terms, a stored procedure is one or more SQL statements saved for later use. Think of them as batch files, although they are not limited to batch processing.

        Stored procedures are complex , and a full description of them would take a long time. This lesson does not intend to explain all the contents of stored procedures, but only gives a brief introduction to let readers understand their functions.


19.2 Why use stored procedures

        We know what stored procedures are, so why use them? There are many reasons, some of the main ones are listed below.

  • Complex operations (as in the previous example) can be simplified by encapsulating processing in an easy-to-use unit.
  • Data consistency is ensured by not requiring iterative establishment of 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 more potential for errors. Preventing errors ensures data consistency.
  • Simplify management of changes. If table names, column names, or business logic (or something else) changes, then only the stored procedure code needs to be changed. 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 requires less work to process the commands, improving performance.
  • There are some SQL elements and attributes that can only be used in a single request, and stored procedures can use them to write more powerful and flexible code.

        In other words, there are three main benefits of using stored procedures, namely, simplicity, security, and high performance . Obviously, they are all important. However, before converting SQL code to stored procedures, there are some pitfalls that must be known.

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

        Despite these drawbacks, stored procedures are very useful and should be used. In fact, most DBMSs come with various stored procedures for managing databases and tables.

        In fact, there is a better solution now.
        Using esProc SPL can replace stored procedures, implement "stored procedures outside the library" or put logic processing in front-end and back-end codes instead of in SQL. Main reasons for wanting to replace stored procedures:

  1. difficult to debug
  2. difficult to write
  3. dyslexia

19.3 Executing stored procedures

        The execution of stored procedures is much more frequent than writing, so we will introduce the execution of stored procedures first. The SQL statement to execute the stored procedure is very simple, namely EXECUTE. 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 LaTour Eiffel in red white and blue' );

        Here a stored procedure called AddNewProduct is executed to add a new product to the Products table. AddNewProduct has four parameters, namely: Vendor ID (primary key of the Vendors table), product name, price, and description. These 4 parameters match the 4 expected variables in the stored procedure (defined as part of the stored procedure itself). This stored procedure adds a new row to the Products table and assigns the passed in attributes to the corresponding columns.

        We noticed that there is another column in the Products table that needs a value, the 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 generated properly, it is best to automate the process of generating this ID (instead of relying on end-user input). That's why this example uses stored procedures .

        Simply put, the primary key is automatically generated.

        Here's what the stored procedure does:

  • Validate the passed data to ensure that all 4 parameters have values;
  • Generate a unique ID to be used as the primary key;

        Insert the new product into the Products table, storing the generated primary key and passed data in the appropriate columns.

  • This is the basic form of stored procedure execution. For a specific DBMS, the following execution options may be included:
  • Parameters are optional, with default values ​​when no parameters are provided;
  • The parameters are not given in order, and the parameter values ​​​​are given in the form of "parameter = value".
  • Output parameters, which allow the stored procedure to update parameters used in the executing application.
  • Data is retrieved with the SELECT statement.
  • Return codes allow a stored procedure to return a value to the executing application.

19.4 Creating stored procedures

        As stated, the writing of stored procedures is important. To get a feel for it, let's look at a simple example of a stored procedure that counts customers with email addresses in a mailing list. Here is the Oracle version of the procedure:

CREATE PROCEDURE 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 parameters of type IN (passing a value to a stored procedure), OUT (returning a value from a stored procedure, like here), and INOUT (both passing a value to and returning a value from a stored procedure). 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 retrieved.

        Calling the Oracle example can look like this:

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

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


        comment code

        All code should be commented, and stored procedures are no exception. Adding annotations does not affect performance, so there are no drawbacks (other than increased writing time). The benefits of commenting code are many, including making it easier for others (and yourself) to understand and safer to modify. The standard way to comment code is to put -- (two hyphens) before it.

Guess you like

Origin blog.csdn.net/qq_57163366/article/details/130244100