create procedure test3()
     begin
     declare i int;
     set i=1;
     while i<5 do
           insert into t_5 select * from t_i;
           set i=i+1;
     end while;
     end;
     |
我有t_1,t_2,t_3表,想引用这三各表,也就是t_i部分,改如何改 才能使得存储过程变成将这三个表的数据写到t_5表中

解决方案 »

  1.   

    create procedure test3()
        begin
        declare i int;
        set i=1;
        while i<5 do
         set @sql = concat('insert into t_5 select * from t_',i);
         PREPARE stmt1 FROM @sql;
         EXECUTE stmt1;
         DEALLOCATE PREPARE stmt1;
              set i=i+1;
        end while;
        end;
        |
      

  2.   

    MYSQL 中不支持表名,字段名上使用变量,只能使用PREPARE ,EXECUTE 来实现。MySQL官方文档 http://dev.mysql.com/doc/refman/5.1/zh/index.html