Mysql:Trim all fields in database
Some years late, but might help others:
This code trims all fields of a the table your_table
.
Could be expanded to work on the whole database in the same way....
SET SESSION group_concat_max_len = 1000000;
SELECT concat('update your_table set ',
group_concat(concat('`',COLUMN_NAME, '` = trim(`',COLUMN_NAME,'`)')),';')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'your_table'
INTO @trimcmd;
PREPARE s1 from @trimcmd;
EXECUTE s1;
DEALLOCATE PREPARE s1;
you expand the query for each column:
UPDATE mytable
SET mycolumn = LTRIM(RTRIM(mycolumn)),
mycolumn2 = LTRIM(RTRIM(mycolumn2)),
...;
Since the question asks for the whole database, here is the script that generates the required SQL. I skip the auto execute, execute it as you like.
-- Set your database name here
SET @my_database:='YOUR_DB_NAME';
SET SESSION group_concat_max_len = 1000000;
SELECT
CONCAT('UPDATE `', @my_database, '`.`', TABLE_NAME,
'` SET ', GROUP_CONCAT(
CONCAT('`', COLUMN_NAME, '` = TRIM(`', COLUMN_NAME, '`)')
ORDER BY ORDINAL_POSITION ASC),
';') AS `query`
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = @my_database
GROUP BY TABLE_NAME
ORDER BY TABLE_NAME ASC;
@ZweiStein Thanks.