MySQL cursors use BULK INSERT or update data

Source: Internet
Author: User

--Loop loops
CREATE PROCEDURE ' test '. ' New_procedure ' () begin--need to define a variable that receives cursor data   DECLARE a CHAR (+);  --Cursor  DECLARE cur cursor for SELECT i from test.t;  --Traversal data end flag  DECLARE done INT DEFAULT FALSE;  --binds the end flag to the cursor  DECLARE CONTINUE HANDLER for not FOUND SET do = TRUE;  --Opening the cursor open  cur;    --Start loop  read_loop:loop    --Extract the data from the cursor, there is only one, and many words are the same;    FETCH cur into A;    --When the declaration is finished, IF done then      LEAVE read_loop;    END IF;    --Here do the loop events you want to do    INSERT into test.t VALUES (a);  END LOOP;  --Closing the cursor close  cur;

END;

Note: the definition of a variable does not have the same name as the key of your select column! Otherwise, fetch into will fail!

Other than that:

If not, insert the data if there is an updated method:

INSERT INTO ' test ' values (A, B) on DUPLICATE KEY UPDATE ' a ' =c;



--While loop
CREATE PROCEDURE Curdemo () BEGIN       Declare stop_flag int default 0;//declares a tag when the cursor state is the last record, modify the variable declare ID int default 0 ;d eclare type int default 0;declare order1 int default 0;declare CUR1 cursor FOR SELECT * from Test1;       Declare CONTINUE HANDLER for SQLSTATE ' 02000 ' SET stop_flag=1;         Open cur1;//cursor       fetch cur1 into id,type,order1; Read data to Cursor while       stop_flag<>1 do//if cursor has next record, loop insert INTO t     Est2 values (id,type,order1);      Fetch cur1 into id,type,order1;       End While;       Close cur1;//closes the cursor end;



MySQL cursors use BULK INSERT or update data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.