Mysql 批量设置未设置默认值字段的默认值。
DROP PROCEDURE IF EXISTS `sp_setdefaultvalue`; CREATE PROCEDURE `sp_setdefaultvalue` (IN databasename VARCHAR(100)) BEGIN DECLARE s_tablename VARCHAR (100); DECLARE s_fieldname VARCHAR (100); DECLARE s_datatype VARCHAR (100); DECLARE cur_table_structure CURSOR FOR SELECT table_name, column_name, data_type FROM INFORMATION_SCHEMA. COLUMNS WHERE table_schema = databasename AND column_default IS NULL ORDER BY table_name; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s_tablename = NULL, s_fieldname = NULL, s_datatype = NULL; OPEN cur_table_structure; FETCH cur_table_structure INTO s_tablename, s_fieldname, s_datatype; WHILE (s_tablename IS NOT NULL) DO IF s_datatype = 'varchar' OR s_datatype = 'char' THEN # 字符型默认值 SET @MyQuery = CONCAT( "alter table `", s_tablename, "` alter column `", s_fieldname, "` set default ''" ); PREPARE MSQL FROM @MyQuery; EXECUTE MSQL; ELSEIF s_datatype = 'int' OR s_datatype = 'tinyint' OR s_datatype = 'smallint' OR s_datatype = 'mediumint' OR s_datatype = 'integer' OR s_datatype = 'bigint' OR s_datatype = 'double' OR s_datatype = 'float' OR s_datatype = 'decimal' OR s_datatype = 'numeric' THEN # 数字型默认值 SET @MyQuery = CONCAT( "alter table `", s_tablename, "` alter column `", s_fieldname, "` set default '0'" ); PREPARE MSQL FROM @MyQuery; EXECUTE MSQL; END IF; #USING @c; FETCH cur_table_structure INTO s_tablename, s_fieldname, s_datatype; END WHILE; CLOSE cur_table_structure; END
使用时只需要运行:
call sp_setdefaultvalue('数据库名称');