1. 程式人生 > >【資料庫-MySql】根據列的型別來統一修改資料庫所有表的資料

【資料庫-MySql】根據列的型別來統一修改資料庫所有表的資料

#如果存在 UpdateDataByColumnType 儲存過程則刪除 UpdateDataByColumnType 儲存過程  
drop procedure if exists UpdateDataByColumnType; 
#如果存在 tmpTable 臨時表則刪除 UpdateDataByColumnType 臨時表  
DROP TABLE if EXISTS tmpTable;  
#建立 UpdateDataByColumnType 儲存過程  
create procedure UpdateDataByColumnType(db char(20))  
begin  
    #申明變數  
    DECLARE tntmp VARCHAR(100);        
    DECLARE tctmp VARCHAR(100); 
		DECLARE indexx int;    
    #建立臨時表  
    create table tmpTable (tablename VARCHAR(1000),columnsname VARCHAR(1000),flag int);   
    #清空臨時表  
    truncate TABLE tmpTable;  
		
    #將需要清空的表插入到臨時表  
    INSERT INTO tmpTable(tablename ,columnsname, flag )
		(SELECT a.TABLE_NAME,a.COLUMN_NAME,0 as flag FROM information_schema.COLUMNS as a
		left JOIN information_schema.TABLES as b on a.TABLE_NAME = b.TABLE_NAME and a.TABLE_SCHEMA = b.TABLE_SCHEMA
		WHERE a.table_schema = db and a.DATA_TYPE in ('datetime','timestamp') and b.TABLE_TYPE ="BASE TABLE");  
          
    #迴圈獲取所有的表明以及刪除狀態      
    SELECT tablename,columnsname into tntmp,tctmp FROM tmpTable WHERE flag = 0 limit 1;  
		
		WHILE tntmp <> '' and tctmp <> '' DO   
			#拼寫刪除語句  
			set @sqlText := concat("update ",tntmp," set ",tctmp ,"='1990-01-01 00:00:00' where ",tctmp," is NULL;");  	  
			prepare stmt from @sqlText;  
			#執行語句  
			execute stmt;  
			#釋放刪除語句  
			deallocate prepare stmt;  
			#更新表狀態  
			UPDATE tmpTable SET flag=1 WHERE tablename = tntmp and columnsname = tctmp;  
			set tntmp = "";	set tctmp = "";
			#選擇一下條語句  
			SELECT tablename,columnsname into tntmp,tctmp FROM tmpTable WHERE flag = 0 limit 1;  
		END WHILE;  
end;  
call UpdateDataByColumnType("hb_dyrmyy");  
#如果存在 UpdateDataByColumnType 儲存過程則刪除 UpdateDataByColumnType 儲存過程  
drop procedure if exists UpdateDataByColumnType;  
#如果存在 tmpTable 臨時表則刪除 UpdateDataByColumnType 臨時表  
DROP TABLE if EXISTS tmpTable;