Sometimes the SQL statement may not be able to achieve the desired data operation purposes, it may be necessary to write some method body, through the cycle of judgment and other operations to achieve the end. Then the implementation of this method in the database needs a stored procedure, the individual think a simple example with annotations can be easily rough to solve most of the problems, of course, to learn more about the words or to see the tutorial documentation, not much said, on the code:
[SQL]View PlainCopy
- CREATE PROCEDURE My_procedure () --Creating a stored procedure
- Begin --Start the stored procedure
- DECLARE my_id varchar (32); --Custom variable 1
- DECLARE my_name varchar (50); --Custom variable 2
- DECLARE done INT DEFAULT FALSE; --Custom control cursor loop variable, default false
- DECLARE my_cursor Cursor for ( SELECT ID, name from t_people); --Define a cursor and enter a result set
- DECLARE CONTINUE HANDLER for Don't FOUND SET done = TRUE; --Bind the control variable to the cursor, and the cursor loop end automatically goes true
- OPEN My_cursor; --Open cursor
- Myloop:loop --Starts the loop body, myloop the custom loop name, and ends the loop with
- FETCH my_cursor into my_id, my_name; --assigns the data order of the cursor currently reading rows to the custom variable
- If do then --determine if the loop continues
- LEAVE Myloop; --End Loop
- END IF;
- --The things you want to do, use custom variables directly in SQL
- UPDATE t_user SET c_name = my_name WHERE id = my_id and RTrim (LTrim (c_name)) = '; --left and right to go space
- COMMIT; --Commit a transaction
- END LOOP Myloop; --End the custom loop body
- CLOSE My_cursor; --Close cursor
- END; --End stored procedure
SQL Call Stored Procedure
[SQL]View PlainCopy
- --SQL execution stored procedure
- Call My_procedure ();
SQL Delete stored procedure
[SQL]View PlainCopy
- --SQL Delete stored procedure
- Drop procedure my_procedure;
End.
"MySQL" stored procedures, cursors, circular simple instances