mysql存储过程从表中设置值

时间:2012-12-18 11:23:45

标签: mysql stored-procedures

我有一个简单的表:

mysql> select * from version;
+----+---------+
| id | version |
+----+---------+
|  1 | 1       |
+----+---------+
1 row in set (0.00 sec)

我需要创建一个存储过程,它将执行某些操作(或不执行任何操作),具体取决于此表的值(确切地说,是此表的唯一行)。

DELIMITER $$
DROP PROCEDURE IF EXISTS upgrade_version $$
CREATE PROCEDURE upgrade_version(current_version INTEGER, script TEXT)
BEGIN
  DECLARE version INT(11);
  SET version = (SELECT `version` FROM `version` WHERE `id` = 1 LIMIT 1);
  SELECT version;
  IF version = current_version + 1 THEN
    PREPARE upgrade_stmt FROM script;
    EXECUTE upgrade_stmt;
    UPDATE `version` SET `version` = `version` + 1 WHERE `id` = 1;
  ENDIF;
END $$
DELIMITER ;

在内部召唤:

CALL upgrade_version(1,'ALTER TABLE ...');

语法错误,mysql返回:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'script;
    EXECUTE upgrade_stmt;
    UPDATE `version` SET `version` = `version`' at line 7 

有什么问题?

3 个答案:

答案 0 :(得分:4)

我不明白你为什么选择" SELECT版本",如果你想选择你必须将它检索到varialbe的数据,那么当你在终端直接使用它时,该语句可以正常工作。你确定你的脚本中有prepared_stmt ..!?可能的解决方法是:

  1. 将varible name版本更改为version_v
  2. 而不是:

    SET version =(SELECT version FROM version WHERE id = 1 LIMIT 1);

    SELECT版本;

  3. 试试这个:

    SELECT `version` INTO Version_v FROM `version` WHERE `id` = 1 LIMIT 1);
    

答案 1 :(得分:4)

试试这个:

DELIMITER $$
DROP PROCEDURE IF EXISTS upgrade_version $$
CREATE PROCEDURE upgrade_version(current_version INT, script TEXT)
BEGIN
  SELECT `version` into @ver FROM `version` WHERE `id` = 1 LIMIT 1;  
  SET @s = script;
  IF @ver = current_version + 1 THEN
    PREPARE upgrade_stmt FROM @s;
    EXECUTE upgrade_stmt;
    DEALLOCATE PREPARE upgrade_stmt;
    UPDATE `version` SET `version` = `version` + 1 WHERE `id` = 1;
  END IF;
END $$
DELIMITER ;

答案 2 :(得分:0)

将值设置为声明变量

       DELIMITER $$
       create procedure Testing()
           begin
            declare Regione int;   
            set Regione=(select  id from users
            where id=1) ;
            select Regione ;
           end $$
         DELIMITER;