I have read many articles about transactions before this article. Most of them are profound and difficult for beginners to understand. Here we will use a very simple example to explain the application of transactions.
First, create a temporary table and fill in some data.
Create Table # tab (ID int, country nvarchar (10), popu INT) insert into # tab values (1, 'China', '123 ') insert into # tab values (2, 'America ', '000000') insert into # tab values (3, 'Canada', '000000') insert into # tab values (4, 'uk ', '123') insert into # tab values (5, 'France', '123') insert into # tab values (6, 'Japan ', '123 ') insert into # tab values (7, 'German ', '000000') insert into # tab values (8, 'Mexico', '50') insert into # tab values (9, 'India ', '123 ')
Now we get a temporary table data.
Second, write a few common transaction statements.
BEGIN TRANSACTION COMMIT ROLLBACK
We have prepared the required data and statements. Take a closer look at the following operations:
-- Execute SQL to start the transaction begin transaction.
Then we delete it directly # Tab
DELETE FROM #tab
No data can be found now.
Now we delete the # tab after the transaction is executed (you must execute the transaction first, otherwise you will directly drop the data to Ko .)
Note: if an error occurs in the previous step, you need to reply to the data. We need to execute
-- Roll back rollback
Our data is back.
NOTE: If we execute the statement correctly in the previous step, do not forget to execute the following sentence (if this statement is not executed, the user will be deadlocked .)
-- Execute commit
It's easy to understand. The transaction is to execute begin transaction first and execute rollback correctly to execute commit. Therefore, this format is often used for transactions.
Begin transaction -- start transaction begin try -- catch exception Delete from # tab commit -- run end trybegin catch rollback without exception -- discover exception rollback end catch
The transaction mechanism is very complicated, but we only need to understand the above sequence when using it. As a result, we can analyze the rollback of fine-grained transactions in the program and use transactions correctly wherever necessary.