mysql 替换所有字段,替换MySQL中的所有字段

这篇博客探讨了如何使用SQL查询来批量替换数据库表中所有列的特定字符。通过结合`CONCAT`,`INFORMATION_SCHEMA.COLUMNS`和预编译语句,可以实现对指定表的所有列进行`REPLACE`操作,从而一次性更新所有出现的目标字符。
摘要由CSDN通过智能技术生成

I need to replace some chars in the columns of a table, by using the REPLACE command.

I know that the REPLACE command needs a column name, then the text to change (in the following example, the 'a' char) and the new text (in the following case, the 'e' char).

UPDATE my_table SET my_column = REPLACE (my_column,'a','e' );

So that executing this command will change all the 'a' occurrences in the my_column column of the my_table table with the 'e' char.

But what if i need to execute the REPLACE command for every column and not just for one? Is this possible?

Thanks

解决方案

Use the following SQL query to generate the SQL queries that you need to replace a value in all columns.

select concat(

'UPDATE my_table SET ',

column_name,

' = REPLACE(', column_name, ', ''a'', ''e'');')

from information_schema.columns

where table_name = 'my_table';

After executing this SQL query simply run all queries to replace all values.

Untested after some googling

Create a stored procedure with a core like this. It can accept the name of the table, the value to find and the value to replace for.

The main idea is to use:

prepared statements for dynamic SQL execution;

cursors to iterate over all columns of a table.

See partial code (untested) below.

DECLARE done INT DEFAULT 0;

DECLARE cur1 CURSOR FOR

SELECT column_name FROM information_schema.columns

WHERE table_name = 'my_table';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN cur1;

REPEAT

SET s = concat(

'UPDATE my_table SET ',

column_name,

' = REPLACE(', column_name, ', ''a'', ''e'');');

PREPARE stmt2 FROM s;

EXECUTE stmt2;

FETCH cur1 INTO a;

UNTIL done END REPEAT;

CLOSE cur1;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值