5

How can I convert the procedure below to MySQL format?

Here is the piece to be converted:

DECLARE @CurrentFirstName varchar(300)
DECLARE @CurrentAge INT

DECLARE CursorName CURSOR FAST_FORWARD FOR 
    SELECT Firstname,Age 
    FROM Customers

OPEN CursorName
FETCH NEXT FROM CursorName INTO @CurrentFirstName, @CurrentAge

WHILE @@FETCH_STATUS = 0
BEGIN
      IF @AGE>60 /*this is stupid but we can apply any complex condition here*/ BEGIN
    insert into ElderCustomers values (@CurrentFirstName,@CurrentAge)
      END


    FETCH NEXT FROM CursorName INTO @CurrentFirstname,@CurrentAge
END

CLOSE CursorName
DEALLOCATE CursorName

Sorry in advance if there is something wrong above

4

1 回答 1

8

MySQL 等价物是这样的:

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;

最大的区别在于循环,当没有更多行要获取时使用 CONTINUE HANDLER 设置标志,并在设置标志时退出循环。(这看起来很难看,但这是在 MySQL 中完成的方式。)

这个例子引出了一个问题,为什么不把它写成(在 SQL Server 和 MySQL 中更有效):

INSERT INTO ElderCustomers (FirstName, Age)
SELECT FirstName, Age
  FROM Customers
 WHERE Age > 60
于 2013-07-26T05:03:23.903 回答