储存过程实现,遍历数据库下所有表,然后操作数据

业务:遍历所有表,使用 insertselect,所有数据,然后把ent_id字段改成为一个新的值。

#定义函数
 drop PROCEDURE if exists insertAsSelectProducts;
 CREATE PROCEDURE insertAsSelectProducts(in i_ent_id int)
BEGIN
  DECLARE tablesNameVar VARCHAR(100);
  DECLARE var_sql VARCHAR(8000);
    DECLARE columnStr varchar(100);
    declare done int;
#查询所有表名
  DECLARE tableName CURSOR FOR select table_name from information_schema.tables where table_schema='库名';
       DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
#我这里的业务是,使用 insertselect,查出所有数据,然后把ent_id字段改成为一个新的值
  open tableName;
    group_loop: LOOP  
  FETCH tableName into  tablesNameVar;
    IF done=1 THEN 
       LEAVE group_loop; 
    END IF;    
#查询所有字段
      select group_concat(column_name) into columnStr 
        from information_schema.columns f 
        where table_name=tablesNameVar and table_schema='库名' and column_name<>'id' and column_name<>'ent_id';
#拼接sql    
  set var_sql = concat_ws(' ','INSERT INTO ', tablesNameVar,'(',columnStr,',ent_id) select ',columnStr,',',i_ent_id,' as ent_id from ', tablesNameVar,'where ent_id=1'); 
  set @sql = var_sql;
  PREPARE s1 from @sql; 
  EXECUTE s1; 
  deallocate prepare s1;
    select @sql;
    
  END LOOP group_loop;
  close tableName;
  # SELECT *  FROM products;
   END

你可能感兴趣的:(java,mysql,存储过程)