START TRANSACTION inside BEGIN … END context or outside and LOOP syntax

后端 未结 1 963
走了就别回头了
走了就别回头了 2021-01-13 12:06

I have two questions about Compound-Statement and Transactions in MySQL.

FIRST:

There are two notes in MySQL Manual:

Note

相关标签:
1条回答
  • 2021-01-13 12:20
    1. Is it allowed to use BEGIN...END just in general flow without creating and using Stored Procedures or Functions?

      No: compound statements can only be used within the body of stored programs.

    2. Is it allowed to use BEGIN...END inside of START TRANSACTION...COMMIT or I have to put START TRANSACTION...COMMIT inside of BEGIN...END?

      START TRANSACTION; and COMMIT; are separate statements. If you want the body of a stored program to contain multiple statements, it will need to enclose those statements in some sort of compound statement block such as BEGIN ... END (which is similar to enclosing a block of statements in braces { ... } within a C-like language).

      That said, you could have a stored program which contains only the single-statement START TRANSACTION; or COMMIT;—such a program would not require any compound statement block and would merely commence a new / commit the current transaction respectively.

      Outside of a stored program, where compound statement blocks are not permitted, you can issue START TRANSACTION; and COMMIT; statements as & when required.

    3. Do I by all means have to use BEGIN...END if I want to use only LOOP? May I just use LOOP syntax without starting BEGIN...END?

      LOOP is also a compound statement block, which is only valid within a stored procedure. It is not necessary to enclose a LOOP block within a BEGIN ... END block, although it is usual (as otherwise it is difficult to perform any required loop initialisation).

    In your case, where you apparently want to insert data into a table from a looping construct, you will either need to:

    • define a stored program in which you use LOOP;

    • iterate a loop in an external program that executes database queries on each iteration; or

    • redefine your logic in terms of sets upon which SQL can directly operate.

    0 讨论(0)
提交回复
热议问题