Mysql存储过程if语法

时间:2014-11-07 12:39:40

标签: mysql stored-procedures

我创建了一个存储过程,该过程应该从列' alt1',' alt2',' alt3'' alt4'中获取值,并使用每个值创建一个新行。 此新值必须具有增量ID。 但是如果条件永远不会满足,虽然我确定有很多alt1,alt2,alt3,alt4都不是空的。

编辑: 在数据库上有很多alt * NOT NULL,但在存储的变量中,Alt *是ALL NULL。

提前谢谢

DELIMITER $$

DROP PROCEDURE IF EXISTS smonta_alias $$
CREATE PROCEDURE smonta_alias ( )
BEGIN
 DECLARE done INT DEFAULT FALSE; 
 DECLARE tname VARCHAR(255);
 DECLARE nuovo_id INT DEFAULT 5000;
 DECLARE alt1 VARCHAR(255);
 DECLARE alt2 VARCHAR(255);
 DECLARE alt3 VARCHAR(255);
 DECLARE alt4 VARCHAR(255);
 DECLARE id INT;
 DECLARE idq INT;

 DECLARE cur1 CURSOR FOR SELECT `alt1` AS alt1, `alt2` AS alt2, `alt3` AS alt3, `alt4` AS alt4, `id` AS id, `id_quota` AS idq FROM `squadra` s WHERE
                                         `s`.alt1 IS NOT NULL OR 
                                         `s`.alt2 IS NOT NULL OR
                                         `s`.alt3 IS NOT NULL OR
                                         `s`.alt4 IS NOT NULL; 
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

 OPEN cur1;
 tables_loop: LOOP
   FETCH cur1 INTO alt1, alt2, alt3, alt4, id, idq;
   IF done THEN
     LEAVE tables_loop;
   END IF;
   IF @alt1 IS NOT NULL THEN   
    SET @s = CONCAT('INSERT INTO `squadra` (id, id_quota, nome_squadra) VALUES (?,?,?)');  
    SELECT @s;
    PREPARE stmtd FROM @s;
    EXECUTE stmtd USING @nuovo_id, @idq, @alt1;
    SET @nuovo_id = @nuovo_id + 1;
   END IF;

   IF @alt2 IS NOT NULL THEN   
    SET @s = CONCAT('INSERT INTO `squadra` (id, id_quota, nome_squadra) VALUES (?,?,?)');  
    SELECT @s;
    PREPARE stmtd FROM @s;
    EXECUTE stmtd USING @nuovo_id, @idq, @alt2;
    SET @nuovo_id = @nuovo_id + 1; 
   END IF;

   IF @alt3 IS NOT NULL THEN   
    SET @s = CONCAT('INSERT INTO `squadra` (id, id_quota, nome_squadra) VALUES (?,?,?)');  
    SELECT @s;
    PREPARE stmtd FROM @s;
    EXECUTE stmtd USING @nuovo_id, @idq, @alt3;
    SET @nuovo_id = @nuovo_id + 1; 
   END IF;

   IF @alt4 IS NOT NULL THEN   
    SET @s = CONCAT('INSERT INTO `squadra` (id, id_quota, nome_squadra) VALUES (?,?,?)');  
    SELECT @s;
    PREPARE stmtd FROM @s;
    EXECUTE stmtd USING @nuovo_id, @idq, @alt4;
    SET @nuovo_id = @nuovo_id + 1;
   END IF;

 END LOOP;
END $$

DELIMITER ;

CALL smonta_alias;

1 个答案:

答案 0 :(得分:0)

在IF语句中使用alt1, alt2, alt2, alt4。不是@alt1, @alt2, @alt3, @alt4。 声明变量时不要使用@。