存储过程中的CALL不起作用

时间:2015-02-08 13:02:55

标签: mysql sql stored-procedures

我在表rel_user_article

中有下一个数据集
+---------+------------+
| user_id | article_id |
+---------+------------+
|       1 |         -1 |
|      97 |        153 |
+---------+------------+

此表格暗示了下一个逻辑:每位作者必须至少有一篇文章,每篇文章必须至少有一位作者。当作者没有文章时,表格必须有假关系:( uid,-1)

当作者添加他的第一篇文章时,必须删除这种假关系。

我有创建新关系和删除假关系的存储过程。 删除假关系看起来像这样:

CREATE PROCEDURE `rel_delete_fake`(IN `ids` TEXT, IN `tbl` VARCHAR(255),
IN `fake_f` VARCHAR(255), IN `real_f` VARCHAR(255))
        MODIFIES SQL DATA
    proc: begin
        if (`ids` = '') then
            leave proc;
        end if;

        set @s = concat('DELETE FROM ', `tbl`, ' WHERE (', `fake_f`, 
                        ' = "-1" AND ', `real_f`, ' IN (', `ids`, '))');

        prepare qr from @s;   
        execute qr;
        deallocate prepare qr;
    end proc

创造"真实"关系看起来像这样:

CREATE DEFINER=`root`@`localhost` PROCEDURE `rel_create`(IN `ids1` TEXT, 
IN `ids2` TEXT, IN `tbl` VARCHAR(255), IN `field1` VARCHAR(255), 
IN `field2` VARCHAR(255))
    MODIFIES SQL DATA
proc: begin
    set @cur = 0;
    set @id1_cur = 0;
    set @id2_cur = 0;

    set @id1_cur_old = NULL;    
    set @id2_cur_old = NULL;

    if (`ids1` = '' or `ids2` = '') then
        leave proc;
    end if;

    set @sql_str = concat('insert into ', `tbl`, ' (', `field1`, ', ', `field2`, ") values (?, ?)");
    prepare qr from @sql_str;
    loop1: loop
        set @cur = @cur + 1;
        set @id1_cur = substring_index(substring_index(`ids1`, ',', @cur), ',', -1);
        set @id2_cur = substring_index(substring_index(`ids2`, ',', @cur), ',', -1);

        if (@id1_cur = @id1_cur_old and @id2_cur = @id2_cur_old) then
            leave proc;
        end if;

        execute qr using @id1_cur, @id2_cur;

        set @id1_cur_old = @id1_cur;
        set @id2_cur_old = @id2_cur;
    end loop loop1;
    deallocate prepare qr;

        -- deleting fake records that became needless
        -- even this doesn't work
    call `rel_delete_fake`('1','rel_user_article','article_id','user_id');
    leave proc;

    -- deleting fake records that became needless
    call `rel_delete_fake`(`ids1`, `tbl`, `field2`, `field1`);
    call `rel_delete_fake`(`ids2`, `tbl`, `field1`, `field2`);
end proc

删除假关系的程序有效。创建关系的过程只会创建新记录,但甚至不会调用rel_delete_fake过程。

对于测试我发出下一个电话:

call `rel_create`('1','153','rel_user_article','user_id','article_id');

并得到结果:

+---------+------------+
| user_id | article_id |
+---------+------------+
|       1 |         -1 |
|       1 |        153 |
|      97 |        153 |
+---------+------------+

为什么不删除此(1,-1)?

1 个答案:

答案 0 :(得分:0)

我发现了错误。必须有"离开loop1;"代替"离开;"在循环中。