Use the cursor and temporary table in the MySQL stored procedure:
- BEGIN
- DECLAREC_egidINTEGER;
- DECLAREDoneINT DEFAULT0;
- DECLAREMy_testCursorCURSOR FOR
- (SELECTCp. tb_electricGroup_idFROMTb_chargingPoleASCpWHERECp. tb_chargeStation_id = 12 );
- DECLARE CONTINUEHANDLERFOR NOTFOUNDSETDone = 1;
- DROP TABLEIf exists tmp_table;
- CREATE TEMPORARY TABLETmp_table (to create a temporary table, write it inDECLARENo syntax errors later
- Tmp_egidINTEGERSome table data formats have changed, such as datetimeTimestamp,BitIs 0, 1, and so on.
- );
- OPENMy_testCursor;
- Emp_loop: LOOP
- FETCHMy_testCursorINTOC_egid; the number of parameters required for each column of the cursor
- IF done = 1THENThe position of this sentence is very important. If it is not placed at the beginning, it may produce a Data repeat.
- LEAVE emp_loop;
- ENDIF;
- INSERT INTOTmp_table (tmp_egid)VALUES(C_egid); insert data into a temporary table
- ENDLOOP emp_loop;
- CLOSEMy_testCursor;
- Select*FromTmp_table;
- TRUNCATETmp_table;
- END
It is worth noting that declare continue handler for not found set done = 1
In a cursor loop, we use done 0 to determine whether to exit the loop. There is no problem in normal insert statements.
However, Handler is triggered when the select statement is used to find null in the cursor, And the done changes from 0 to 1.
Therefore, if the cursor contains a select statement, you can use other methods, such as the while loop. The following is an example of exiting the while loop by determining the length of the result set.
- SELECT COUNT(*)INTO@ PageCountFROMTmp_bwGetChargePoleCommunicationtable;
- SET@ Num = 0;
- OPENMy_testCursor;
- WHILE @ num <@ pageCount DO
- SET@ Num = @ num + 1;
- FETCHMy_testCursorINTOParam_id, param_ip, param_port, param_key;
- IF param_keyIS NULL THEN
- SELECTKiosk_keyINTO@ TmpParam_keyFROMTb_kioskWHEREKiosk_id = (SELECTTb_kiosk_idFROMTb_chargingPoleWHERECp_id = param_id );
- UPDATETmp_bwGetChargePoleCommunicationtableSETTmp_key = @ tmpParam_keyWHERETmp_id = param_id;
- ENDIF;
- ENDWHILE;
- CLOSEMy_testCursor;