为多个insert和alter table查询创建存储过程

时间:2016-03-25 12:23:30

标签: php mysql stored-procedures

$link->query("DROP TABLE IF EXISTS table2");           
$link->query("CREATE TABLE table2 (newcol BIGINT UNSIGNED  PRIMARY KEY)");
$result=$link->query("select col1 from table1");
while($data=$result->fetch_array(MYSQL_ASSOC))
{

    $link->query("insert into table2 (newcol) values($data['col1']);
    $link->query(""ALTER TABLE table2 ADD  `".$data['col1']."` BIGINT DEFAULT 0"");
  }

我想做的是

  1. 创建一个表格" table2"一列" newcol"。
  2. 选择" col1"的所有值来自" table1"和
  3. 来自col1

    table1的每个值

    - 将值插入" newcol" table2

    - 将一列namedvalue col1 table 1添加到" table2"

  4.   

    上面的代码在php中看起来非常整洁有效,但问题是它需要花费一些时间。所以我认为将它们转换为MySQL存储过程更好。因为我对存储过程不熟悉,非常很困惑。请帮帮我们。

2 个答案:

答案 0 :(得分:1)

当然,我无法测试它,但它在我的计算机上正在编译。

DELIMITER //

CREATE PROCEDURE `myProcedure` ()
BEGIN

    DECLARE _done BOOLEAN DEFAULT FALSE;
    DECLARE _myField BIGINT UNSIGNED DEFAULT 0;

    /* the cursor here is like your PDOStatement 
    * it is used to fetch data */
    DEClARE _myReader CURSOR FOR
        SELECT `col1` FROM `table1`;

    /* it is not very elegant, but we need to throw an exception
    * to break the loop */    
    DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET _done = TRUE;

    DROP TABLE IF EXISTS `table2`;

    CREATE TABLE `table2` (
        `newcol` BIGINT UNSIGNED PRIMARY KEY
    );

    /* you open your PDOStatement */
    OPEN _myReader;

    /* myLoop is like a GOTO*/
    myLoop: LOOP

        /* $result->fetch_array(MYSQL_ASSOC)*/
        FETCH _myReader INTO _myField;

        /* if the no data exception had been thrown, 
        * goto the end of the loop */
        IF _done = 1 THEN 
            LEAVE myLoop;
        END IF;


        INSERT INTO `table2` (newcol) VALUES (_myField);

        ALTER TABLE `table2` ADD `_myField` BIGINT DEFAULT 0;

    END LOOP myLoop;

    /* close your PDO object */     
    CLOSE _myReader;

END //

答案 1 :(得分:1)

JonathanParentLévesque帮助我了解了内部存储过程的循环如何工作,以及获得与上述问题中描述的php代码等效的存储过程的整体结构。 /> 谢谢 JonathanParentLévesque
但是在他的代码中使用变量添加列名不能按预期工作。

  

最后我想出来了

BEGIN

    DECLARE _done BOOLEAN DEFAULT FALSE;
    DECLARE _myField BIGINT DEFAULT 0;

    DEClARE _myReader CURSOR FOR
    SELECT id FROM `tags`;

    DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET _done = TRUE;

    DROP TABLE IF EXISTS `tag_similarity`;

    CREATE TABLE `tag_similarity` (
        `tag` BIGINT UNSIGNED PRIMARY KEY
    );

    OPEN _myReader;

    myLoop: LOOP

        FETCH _myReader INTO _myField;

        IF _done = 1 THEN 
            LEAVE myLoop;
        END IF;


        INSERT INTO `tag_similarity` (tag) VALUES (_myField);
        SET @sql = CONCAT('ALTER TABLE tag_similarity ADD `',_myfield,'` BIGINT DEFAULT 0');
      PREPARE stmt FROM @sql;
         EXECUTE stmt ;
         DEALLOCATE PREPARE stmt;
      END LOOP myLoop;

    CLOSE _myReader;

END