如何将SQL Server游标转换为等效的MySQL
如何将下面的过程转换为MySQL格式 下面是要转换的片段:如何将SQL Server游标转换为等效的MySQL,mysql,sql-server-2008-r2,cursor,Mysql,Sql Server 2008 R2,Cursor,如何将下面的过程转换为MySQL格式 下面是要转换的片段: 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,
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
如果上面有问题,请提前道歉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处理程序设置一个标志,当设置标志时退出循环。(这看起来很难看,但MySQL就是这样做的。)
这个例子引出了这样一个问题:为什么不将其写入(在SQL Server和MySQL中都更有效),原因如下:
INSERT INTO ElderCustomers (FirstName, Age)
SELECT FirstName, Age
FROM Customers
WHERE Age > 60