Search code examples
oracle-databasestringplsqlvarchartrim

How to trim all columns in all rows in all tables of type string?


In Oracle 10g, is there a way to do the following in PL/SQL?

for each table in database
  for each row in table
    for each column in row
      if column is of type 'varchar2'
        column = trim(column)

Thanks!


Solution

  • Of course, doing large-scale dynamic updates is potentially dangerous and time-consuming. But here's how you can generate the commands you want. This is for a single schema, and will just build the commands and output them. You could copy them into a script and review them before running. Or, you could change dbms_output.put_line( ... ) to EXECUTE IMMEDIATE ... to have this script execute all the statements as they are generated.

    SET SERVEROUTPUT ON
    
    BEGIN
      FOR c IN
        (SELECT t.table_name, c.column_name
           FROM user_tables t, user_tab_columns c
           WHERE c.table_name = t.table_name
             AND data_type='VARCHAR2')
      LOOP
    
        dbms_output.put_line(
                          'UPDATE '||c.table_name||
                          ' SET '||c.column_name||' = TRIM('||c.column_name||') WHERE '||
                          c.column_name||' <> TRIM('||c.column_name||') OR ('||
                          c.column_name||' IS NOT NULL AND TRIM('||c.column_name||') IS NULL)'
                         );
      END LOOP;
    END;