How to convert a SQL Server cursor to MySQL equivalent

前端 未结 1 893
谎友^
谎友^ 2020-12-18 08:44

How can I convert the procedure below to MySQL format?

Here is the piece to be converted:

DECLARE @CurrentFirstName varchar(300)
DECLARE @CurrentAge          


        
相关标签:
1条回答
  • 2020-12-18 09:14

    The MySQL equivalent would be something like this:

    BEGIN
      DECLARE CurrentFirstName VARCHAR(300);
      DECLARE CurrentAge INT;
      DECLARE done INT DEFAULT FALSE;
      DECLARE CursorName CURSOR FOR
        SELECT FirstName, Age FROM Customers;
      DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
      OPEN CursorName;
      myloop: LOOP
        FETCH CursorName INTO CurrentFirstName, CurrentAge;
        IF done THEN
          LEAVE myloop;
        END IF;
        IF CurrentAge > 60 THEN
          insert into ElderCustomers values (CurrentFirstName,CurrentAge);
        END IF;
      END LOOP;
      CLOSE CursorName;
    END;
    

    The big difference is in the loop, using the CONTINUE HANDLER to set a flag when there are no more rows to fetch, and exiting the loop when the flag is set. (That looks ugly, but that's the way it's done in MySQL.)

    This example begs the question why this isn't written (more efficiently, in both SQL Server and MySQL) as:

    INSERT INTO ElderCustomers (FirstName, Age)
    SELECT FirstName, Age
      FROM Customers
     WHERE Age > 60
    
    0 讨论(0)
提交回复
热议问题