我想在动态查询中的变量中存储一个值,然后想要在检查此变量时运行另一个查询

时间:2014-01-31 09:51:51

标签: mysql stored-procedures

我想在我的过程的后面部分使用i_count变量,但是没有赋值。

当我使用一般查询而不是前面的动态查询时,无论如何它的运行完美。

DROP PROCEDURE IF EXISTS `common2`;
CREATE PROCEDURE `common2`(tablename VARCHAR(50),attr_name VARCHAR(50),pk BIGINT(255),i_block_id BIGINT(255))
BEGIN
DECLARE i_count INTEGER(255);

set @sql_text = concat('SELECT COUNT(',pk,') INTO  @i_count FROM ',tablename, ' WHERE ',attr_name,'=1 AND ',pk,'=',i_block_id);

prepare statement from @sql_text;


    execute statement;
#deallocate prepare statement; 

IF (i_count=1) THEN
set @sql_text1 = concat('UPDATE ',tablename, '  SET ',attr_name,'=0 WHERE ',attr_name,'=1 AND ',pk,'=',i_block_id);
prepare statement1 from @sql_text1;
    execute statement1;
#deallocate prepare statement; 
   ELSE
set @sql_text2 = concat('UPDATE ',tablename, ' SET ',attr_name,'=1 WHERE ',attr_name,'=0 AND ',pk,'=',i_block_id);
prepare statement2 from @sql_text2;
    execute statement2;
#deallocate prepare statement; 

   END IF;




END;

1 个答案:

答案 0 :(得分:0)

这两个变量之间存在差异。以@开头的变量是user defined variables。声明的变量是local variables

像这样写:

delimiter $$
DROP PROCEDURE IF EXISTS `common2`;
CREATE PROCEDURE `common2`(tablename VARCHAR(50),attr_name VARCHAR(50),pk BIGINT(255),i_block_id BIGINT(255))
BEGIN

set @i_count = 0;

set @sql_text = concat('SELECT COUNT(',pk,') INTO  @i_count FROM ',tablename, ' WHERE ',attr_name,'=1 AND ',pk,'=',i_block_id);

prepare statement from @sql_text;


    execute statement;
#deallocate prepare statement; 

IF (@i_count=1) THEN
set @sql_text1 = concat('UPDATE ',tablename, '  SET ',attr_name,'=0 WHERE ',attr_name,'=1 AND ',pk,'=',i_block_id);
prepare statement1 from @sql_text1;
    execute statement1;
#deallocate prepare statement; 
   ELSE
set @sql_text2 = concat('UPDATE ',tablename, ' SET ',attr_name,'=1 WHERE ',attr_name,'=0 AND ',pk,'=',i_block_id);
prepare statement2 from @sql_text2;
    execute statement2;
#deallocate prepare statement; 

   END IF;

END $$
delimiter ;