How to convert a SQL Server cursor to MySQL equivalent(如何将 SQL Server 游标转换为 MySQL 等价物)
问题描述
如何将下面的程序转换为 MySQL 格式?
How can I convert the procedure below to MySQL format?
这是要转换的部分:
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 等价物是这样的:
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;
最大的区别在于循环,当没有更多行要获取时使用 CONTINUE HANDLER 设置标志,并在设置标志时退出循环.(这看起来很难看,但在 MySQL 中就是这样做的.)
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.)
这个例子引出了一个问题,为什么不把它写成(在 SQL Server 和 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
这篇关于如何将 SQL Server 游标转换为 MySQL 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 SQL Server 游标转换为 MySQL 等价物


- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01