1

I have a table with several columns, and I would like to eliminate spaces value (' ') from the values. The query is:

update table
set column_name = trim(both ' ' from column_name)
where column_name like '% '

and since the table contains around 55 columns so probably a loop would be a feasible idea instead of writing update statement for each and every column.

First I checked if looping is working:

declare
    column_name varchar2(2048);
    cursor pointer is
         select column_name into column_name from user_tab_cols where table_name = 'TABLE_NAME';

begin 
    for x in pointer
    loop
        dbms_output.put_line(x.column_name);
    end loop;
end;

yes, it is working. I get column names in dbms_output window.

Now, Here is what I am trying to do which doesn't seem to work:

declare
    column_var varchar2(2048);
    cursor pointer is
         select column_name into column_var from user_tab_cols where table_name = 'TABLE_NAME';

begin 
    for x in pointer
    loop
         update table_name
         set x.column_var = trim(both ' ' from x.column_var)
         where x.column_var like '% ';
         commit;
    end loop;
end;

This is, unfortunately not working. This is error I get:

ORA-06550: line 11, column 18:
PLS-00302: component 'COLUMN_VAR' must be declared.
ORA-06550: line 11, column 16:
PL/SQL: ORA-00904: "X"."COLUMN_VAR": invalid identifier
ORA-06550: line 9, column 10:
PL/SQL: SQL Statement ignored

Any idea where I am going off the track?

Thanks in advance :-)

2 Answers 2

3

I think you need to provide the actual column name, rather than the string representing the column name in the statement. Would an execute immediate work for you?

declare
    column_var varchar2(2048);
    cursor pointer is
         select column_name into column_var from user_tab_cols where table_name = 'TABLE_NAME';

begin 
   for x in pointer
   loop
         execute immediate 
             'update table_name ' ||
             'set '|| x.column_var ||' = trim(both '' '' from '|| x.column_var ||')'||
             'where '|| x.column_var ||' like ''% ''';
         commit;
    end loop;
end;
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use dynamic sql for this

    BEGIN
      FOR t IN (select column_name from user_tab_cols where table_name = 'MyTable')
                   LOOP
     EXECUTE IMMEDIATE
         'update MyTable set '||t.column_name||' = trim(both '' '' from '||t.column_name||') where '||t.column_name||' like ''% ''';

      END LOOP;

    END;

/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.