我想在完整数据库中用另一个字符串替换字符串。假设数据库名称为" A"它包含101个表。我想改变" subhojit"到" jeet"在所有表格的列中,如果它包含" subhojit"。
MySql可以吗? 需要写程序吗? 请回复。
答案 0 :(得分:0)
update thetable set thecol = replace(thecol, 'subhojit', 'jeet')
where thecol like '%subhojit%';
来自here。
答案 1 :(得分:0)
这有点粗糙和准备就绪(例如异常处理)。但希望你可以为自己的目的整理它:
DELIMITER $$
CREATE PROCEDURE `replace_value_in_all_cols`(IN i_schema varchar(250),IN i_fromVal varchar(250),IN i_toVal varchar(250), OUT o_errMessage varchar(250))
BEGIN
ALL_TEXT_COLUMNS : BEGIN
DECLARE noMoreRows boolean;
DECLARE db varchar(250);
DECLARE tbl varchar(250);
DECLARE col varchar(250);
DECLARE allTextCols CURSOR FOR
select c.table_schema,c.table_name,c.column_name
from information_schema.columns c
where c.table_schema = i_schema
and lower(data_type) in ('char','text','varchar');
DECLARE EXIT HANDLER for SQLEXCEPTION set o_errMessage := "Some error message";
declare continue handler for not found set noMoreRows := true;
open allTextCols;
UPDATE_LOOP : loop
fetch allTextCols
into db,tbl,col;
if noMoreRows then
close allTextCols;
leave UPDATE_LOOP;
end if;
SET @update_stmt:=CONCAT("UPDATE ",db,".",tbl," SET ",col," = replace(",col,",'",i_fromVal,"','",i_toVal,"');");
PREPARE update_stmt FROM @update_stmt;
EXECUTE update_stmt;
DEALLOCATE PREPARE update_stmt;
end loop UPDATE_LOOP;
END ALL_TEXT_COLUMNS;
END$$
DELIMITER ;
然后你可以做类似的事情:
call `replace_value_in_all_cols`("A",'subhojit','jeet', @err);