The difference and connection between database transactions, stored procedures, functions, and triggers

1. 【Concept of Affairs】

Transaction refers to a collection of operations that constitute a single logical unit of work, which is either completely executed or not executed at all.

1. If some operations in the transaction are not successfully completed, all operations in the transaction need to be rolled back and return to the state before the transaction is executed (either fully executed or not executed);

2. At the same time, the transaction has no effect on the execution of the database or other transactions, and all transactions seem to be running independently.

2. [Business example]

Use a commonly used example of "A account transfers money to B account" to illustrate how to ensure the accuracy and completeness of data through database transactions. Those who are familiar with relational database transactions know that from account A to account B, 6 operations are required, namely:

1. Read out the balance from account A (500)

2. Perform a subtraction operation on account A (500-100)

3. Write the result back to account A (400)

4. Read out the balance from account B (500)

5. Adding to account B (500 + 100)

6. Write the result back to account B (600)

Three, [transaction characteristics]

Not any sequence of operations on the database is a database transaction. A transaction should have four attributes: atomicity, consistency, isolation, and durability. These four attributes are usually called ACID characteristics.

1. Atomicity: All operations of a transaction on the database are an indivisible unit of work. These operations are either all executed or not executed;

Ensure that all procedures 1-6 are executed or not executed.

Once a problem occurs during the execution of a certain step, you need to perform a rollback operation.

If account B is suddenly unavailable (such as being cancelled) when step 5 is executed, then all previous operations should be rolled back to the state before the transaction was executed.

2. Consistency: The transaction should ensure that the state of the database changes from one consistent state to another consistent state. The meaning of a consistent state is that the data in the database should meet the integrity constraints;

Before the transfer, there is a total of 500 + 500 = 1000 yuan in the accounts of A and B.

After the transfer, there should also be a total of 400 + 600 = 1000 yuan in the accounts of A and B.

In other words, the state of the data changes from one state to another after the transaction operation is executed. At the same time, consistency can also ensure that the account balance will not become negative, etc.

Note: Consistency and atomicity are closely related. The destruction of atomicity may lead to inconsistencies in the database. Data consistency issues are not all related to atomicity.

For example, in the above example, in step 5, only 50 yuan was added when adding to account B. Then, the process can conform to the atomicity, but there is a problem with the consistency of the data. Therefore, the atomicity and consistency of transactions are indispensable.

3. Isolation (Isolation): When multiple transactions are executed concurrently, the execution of one transaction should not affect the execution of other transactions;

In the entire process of transferring money from A to B, as long as the transaction has not been committed (commit), the amount of money in the two accounts will not change when the A account and the B account are inquired.

If while A transfers money to B, another transaction performs the transfer operation from C to B, then when both transactions are over, the money in account B should be the money transferred from A to B plus the money transferred from C to B's money plus his original money.

4. Durability: Once a transaction is committed, its modifications to the database should be permanently stored in the database.

For example, when we use the update statement to update a record in the database, a database transaction will be opened by default. When we execute (F8) this statement, we query this record again, it has been updated, but the transaction has not been committed, and the transaction has not Have an impact on the database. At this time, if the query window is closed (a failure occurs), the database record has not been affected. Only after the transaction is committed, the record will be truly and permanently updated.

 

Four, [concurrency of transactions]

Transaction concurrency: A database may have multiple access clients, and these clients can access the database concurrently. The same data in the database may be accessed by multiple transactions at the same time. If necessary isolation measures are not taken, various concurrency will occur. Problems, destroy the integrity of the data.

Concurrency problems boil down: data problems (dirty reads, phantom reads, non-repeatable reads), data update problems (updates lost)

1. [The concept of stored procedures]

① Stored Procedure (Stored Procedure) is a set of SQL statements to complete a specific function. After being compiled, it is stored in the database.

② A stored procedure is an important object in the database. The user executes it by specifying the name of the stored procedure and giving parameters (either with or without parameters).

③ A stored procedure is a procedure written by flow control and SQL statements. This procedure is compiled and optimized and stored in the database server.

④ The stored procedure can be executed by the application through a call, and the user is allowed to declare variables.

⑤ At the same time, the stored procedure can receive and output parameters, return the status value of the execution of the stored procedure, or nested calls.

2. [Advantages of stored procedures]

① The use of stored procedures greatly enhances the function and flexibility of the SQL language.

Stored procedures can be written with flow control statements, which have strong flexibility and can complete complex judgments and more complex calculations.

② The security and integrity of the data can be guaranteed.

Through stored procedures, users without permission can access the database indirectly under control, thereby ensuring data security.

Through stored procedures, related actions can occur together, so that the integrity of the database can be maintained. (Just like the atomicity of the transaction: either all SQL statements in the transaction are executed successfully, or all SQL statements are unsuccessful)

③ Before running the stored procedure, the database has performed grammatical and syntactic analysis on it, and has given an optimized execution plan.

This compiled process can greatly improve the performance of SQL statements.

Since most of the work of executing the SQL statement has been completed (because it has been compiled in advance), the stored procedure can be executed at an extremely fast speed.

④ It can reduce the amount of network communication.

The client only needs to transfer the stored procedure name and related parameters to call the stored procedure. Compared with the transmission of SQL statements, the amount of natural data is much less (reflected during remote access).

⑤ Stored procedures are compiled only when they are created, and there is no need to recompile each time the stored procedure is executed. Generally, SQL statements are compiled every time they are executed, so the use of stored procedures can increase the execution speed of the database.

⑥ When performing complex operations on the database (such as Update, Insert, Query, Delete on multiple tables), this complex operation can be encapsulated with a stored procedure and used in conjunction with the transaction processing provided by the database.

For example, each step of the operation of the database is completed by a transaction, and these transactions are all placed in a stored procedure.

⑦ Stored procedures can be reused, which can reduce the workload of database developers.

⑧ High security, it can be set that only certain users have the right to use the specified stored procedure

3. [Disadvantages of stored procedure]

① Debugging is troublesome: but debugging with PL/SQL Developer is very convenient! Make up for this shortcoming.

② Transplantation problem: The database-side code is of course related to the database. But if it is an engineering project, there is basically no migration problem.

③ Recompilation problem: Because the back-end code is compiled before running, if the object with reference relationship changes, the affected stored procedures and packages will need to be recompiled (but it can also be set to automatically compile at runtime).

For example, A stored procedure calls B stored procedure and uses B's return value as a parameter. If B's ​​parameter or return value changes, it will affect A that called her. At this time, the stored procedure must be recompiled and set to run time. Automatic compilation.

④ Maintenance is more difficult: If a large number of stored procedures are used in a program system, the data structure will change with the increase of user demand when the program is delivered to use, and then there are related problems of the system. Finally, if the user wants to maintain the The system can be said to be difficult and difficult, and the cost is unprecedented, and it is more troublesome to maintain.

4. [Types of stored procedures]

① System storage process: generally starts with sp_, used to set various system settings, obtain configuration information, and related management tasks.

② Local stored procedure: A stored procedure created by a user is a stored procedure that is created by the user and completes a specific function. In fact, the generally referred to as a stored procedure refers to a local stored procedure.

③ Temporary storage process: Divided into two kinds of storage process:

The first is a local temporary stored procedure, with the pound sign (#) as the first character of its name, the stored procedure will become a local temporary stored procedure stored in the tempdb database, and only the user who created it can execute it;

The second is the global temporary stored procedure, starting with two pound signs (##), the stored procedure will become a global temporary stored procedure stored in the tempdb database. Once the global temporary stored procedure is created, it will connect to any server in the future. Users can execute it, and no specific permissions are required.

④ Remote stored procedures: In SQL Server2005, remote stored procedures (Remote Stored Procedures) are stored procedures located on a remote server. You can usually use distributed queries and EXECUTE commands (in the SQL*Plus command line window) to execute a remote storage process.

⑤ Extended stored procedures: Extended stored procedures (Extended Stored Procedures) are stored procedures that users can use external programming languages ​​to write, and the names of extended stored procedures usually start with xp_.

5. [Characteristics of stored procedures]

1. The difference between stored procedures and functions

①Return value: The function can only return one variable, while the stored procedure can return multiple. For stored procedures, you can return parameters, such as a record set, while functions can only return values ​​or table objects

② The stored procedure is generally executed as an independent part (EXECUTE statement execution), and the function can be called as a part of the query statement (SELECT call), because the function can return a table object, so it can be located in the query statement After the FROM keyword. Stored procedures are not available in SQL statements, but functions can be used.

③ The function realized by the stored procedure is a little more complicated, while the function realized by the function is more targeted and single.

2. The difference between stored procedures and transactions

① Storage location: The transaction is called in the program, saved in the code that calls and implements it, and the stored procedure can be called directly on the database client and stored in the database after being compiled.

②Operation mode: The SQL statement in the transaction is executed every time it is called. The stored procedure is compiled in advance, and the SQL statement in it is not executed every time it is called.

③The transaction has strict consistency and atomicity, and the security is high. The stored procedure does not have these characteristics. When performing some complex operations, in order to ensure the accuracy of the operation, you can call the transaction in the stored procedure and then judge the transaction Whether the execution result is successful to ensure the accuracy of the operation.

3. Trigger

①Concept and function

Trigger is a special type of stored procedure, which is different from the stored procedure we introduced earlier. Triggers are mainly triggered by events to be executed, and stored procedures can be directly called by the name of the stored procedure. When operations such as Update, Insert, Delete are performed on a table, SQL Server will automatically execute the SQL statements defined by the trigger to ensure that the data processing must comply with the rules defined by these SQL statements.

The main function of triggers is that they can achieve complex referential integrity and data consistency that cannot be guaranteed by primary keys and foreign keys. In addition, the trigger has many other different functions:

(1) Enforce restriction

Triggers can implement more complex constraints than CHECK statements.

(2) Auditing changes

Triggers can detect operations in the database, so that unauthorized specified updates and changes in the database are not allowed.

(3) Cascaded operation.

Triggers can detect operations in the database and automatically cascade to affect the contents of the entire database. For example, a trigger on a table contains data operations (such as delete, update, and insert) on another table, and this operation causes the trigger on the table to be triggered.

(4) Stored procedure invocation.

In response to database updates, triggers can call one or more stored procedures, and can even operate outside the DBMS (database management system) itself through the call of external procedures.

It can be seen that triggers can solve some problems such as advanced business rules or complex behavior restrictions and the realization of customized records. For example, a trigger can find out the difference in the state of a table before and after data modification, and perform certain processing based on this difference. In addition, multiple triggers of the same type (Insert, Update, Delete) of a table can take a variety of different treatments for the same data operation.

In general, trigger performance is usually low. When the trigger is run, most of the system processing time is spent on the processing of referencing other tables, because these tables are neither in memory nor on the database device, and delete tables and insert tables are always in memory. It can be seen that the location of other tables referenced by the trigger determines the length of time the operation will take.

Guess you like

Origin blog.csdn.net/smilejiasmile/article/details/108114853