Resizing each VARCHAR column in a database table - Oracle 11g

I have at least 65 VARCHARcolumns in a table Athat I would have to change from X bytesto X char. I was hoping to find an easier way than running the command ALTER TABLE A MODIFY..65 times.

Can someone please help me, how can I do this faster?

+3
source share
4 answers

You can write some dynamic SQL. Assuming the table is in the current schema

DECLARE
  l_sql_stmt VARCHAR2(1000);
BEGIN
  FOR t IN (SELECT * FROM user_tab_cols WHERE table_name = 'A')
  LOOP
    l_sql_stmt := 'ALTER TABLE ' || t.table_name || ' MODIFY (' || 
                     t.column_name || ' varchar2(' || t.char_length || ' char))';
    EXECUTE IMMEDIATE l_sql_stmt;
  END LOOP;
END;

What you can see below

SQL> ed
Wrote file afiedt.buf

  1  create table foo(
  2    col1 varchar2(10 byte),
  3    col2 varchar2(20 byte)
  4* )
SQL> /

Table created.

DECLARE
  l_sql_stmt VARCHAR2(1000);
BEGIN
  FOR t IN (SELECT * FROM user_tab_cols WHERE table_name = 'FOO')
  LOOP
    l_sql_stmt := 'ALTER TABLE foo MODIFY (' || 
                     t.column_name || ' varchar2(' || t.char_length || ' char))';
    EXECUTE IMMEDIATE l_sql_stmt;
  END LOOP;
END;


SQL> desc foo;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COL1                                               VARCHAR2(10 CHAR)
 COL2                                               VARCHAR2(20 CHAR)
+5
source

You can try something ugly as if

 select 'ALTER TABLE '||table_name|
        ' MODIFY ('||column_name||' VARCHAR2('||char_length||' char));'
   from all_tab_cols
   where table_name='A' and
         datatype like 'VARCHAR2%';

copy the result grid and paste it and run in your preferred sql editor

+4

- , - :

:

  FOR t IN (SELECT * FROM user_tab_cols WHERE table_name = 'A')

Grokster:

FOR x IN (SELECT * FROM user_tab_cols WHERE table_name = 'A' AND datatype LIKE 'VARCHAR%')

Please note that Grokster correctly validates the data type, and does not try to convert all columns to varchar2!

+1
source
BEGIN
    FOR x IN (SELECT * FROM user_tab_cols WHERE table_name = 'A' AND datatype LIKE 'VARCHAR%')
    LOOP
        EXECUTE IMMEDIATE 'ALTER TABLE '||x.table_name||' MODIFY '||x.column_name ||' VARCHAR2('||x.char_length||' CHAR)';
    END LOOP; 
END;
/
0
source

All Articles