热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

过程中的光标不返回任何值-CursorinProceduredoesnotreturnanyvalues

Ihaveadatabasewheretemptablesarecreated,thosetablenamesarerandomlygeneratedandsaved

I have a database where temp tables are created, those table names are randomly generated and saved in Checkouts.unid. I want to drop all those tables and truncate the table Checkouts. I thought the niftiest solution would be a procedure, but it will not work:

我有一个创建临时表的数据库,这些表名是随机生成的并保存在Checkouts.unid中。我想删除所有这些表并截断表Checkouts。我认为最麻烦的解决方案是一个程序,但它不起作用:

DROP PROCEDURE IF EXISTS `spCheckoutsCleanup`;
CREATE PROCEDURE `spCheckoutsCleanup` ()
  SQL SECURITY INVOKER
BEGIN
    DECLARE `t` VARCHAR(64);
    DECLARE `ch` CURSOR FOR SELECT `unid` FROM `Checkouts`;
    OPEN `ch`;

    drop_tables: LOOP
        FETCH `ch` INTO `t`;
        DROP TABLE IF EXISTS `t`;
    END LOOP;

    CLOSE `ch`;
    TRUNCATE TABLE `Checkouts`;
END

I always get "No data - zero rows fetched, selected, or processed" although those tables are there and the table Checkouts is not empty though.

我总是得到“没有数据 - 零行提取,选择或处理”,虽然这些表在那里,表Checkouts不是空的。

2 个解决方案

#1


You have to add something like this in order to end your loop:

你必须添加这样的东西才能结束你的循环:

DECLARE CONTINUE HANDLER FOR NOT FOUND SET ...;

See example in the documentation.. E.g. ...

请参阅文档中的示例..例如...

DROP PROCEDURE IF EXISTS `spCheckoutsCleanup`;
CREATE PROCEDURE `spCheckoutsCleanup` ()
  SQL SECURITY INVOKER
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE `t` VARCHAR(64);
    DECLARE `ch` CURSOR FOR SELECT `unid` FROM `Checkouts`;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET dOne= TRUE;

    OPEN `ch`;

    drop_tables: LOOP
        FETCH `ch` INTO `t`;
        IF done THEN
           LEAVE drop_tables;
        END IF;
        DROP TABLE IF EXISTS `t`;
    END LOOP;

    CLOSE `ch`;
    TRUNCATE TABLE `Checkouts`;
END

Otherwise you will get an error once you reached the end of your cursor.

否则,一旦到达光标的末尾,就会出现错误。

#2


I got it working with this:

我得到了它:

DROP PROCEDURE IF EXISTS `spCheckoutsCleanup`;
CREATE PROCEDURE `spCheckoutsCleanup` ()
  SQL SECURITY INVOKER
BEGIN
    DECLARE done int DEFAULT 0;
    DECLARE t CHAR(64);
    DECLARE ch CURSOR FOR SELECT `unid` FROM `Checkouts`;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET dOne= 1;
    OPEN ch;

    drop_table: LOOP
        FETCH ch INTO t;
        IF dOne= 1 THEN
            LEAVE drop_table;
        END IF;
        SET @sql := CONCAT('DROP TABLE IF EXISTS `', t, '`'); 
        PREPARE dropt FROM @sql; 
        EXECUTE dropt;
    END LOOP;

    CLOSE ch;
    TRUNCATE TABLE `Checkouts`;
END;
CALL spCheckoutsCleanup;

推荐阅读
author-avatar
晶晶9930_195
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有