3

I want to call create table/ alter table command from a procedure. Is it possible?

My requirement is to change the datatype of a column in all tables. So, I am just getting the column name from user_tab_cols. Now I want to create a temp table which requires create statement .. but i am unable to use that within a proc.

Can anyone please help me out?

1
  • In Oracle there is no need to create temp tables on the fly. You should consider using a Global Temporary Table - it is created once only, but each session can use it as if they had their own private copy of it (and the data in it is automatically cleared when the session ends (or at commit time, if you prefer)). Commented Jan 6, 2010 at 12:06

2 Answers 2

11

I presume from the reference to USER_TAB_COLUMNS that this is Oracle. ALTER and CREATE statements are DDL, which we cannot execute directly in PL/SQL. However, there are a couple of ways around this restriction: EXECUTE IMMEDIATE and DBMS_UTILITY.EXEC_DDL(). I will use EXECUTE IMMEDIATE in the following example.

begin
    for lrec in ( select table_name from user_tab_columns
                  where column_name = 'UNIVERSAL_COLUMN_NAME')
    loop
        execute immediate 'alter table '||lrec.table_name||
                               ' modify UNIVERSAL_COLUMN_NAME varchar2(255)';
    end loop;
end;

Note that the usual restrictions apply: the new datatype has to be compatible with the existing datatype (unless the column is empty), and things are trickier with some specilaized datatypes like CLOBs.

edit

I haven't addressed the CREATE TABLE statement. The principle is the same, it is just longer to type out. Besides, I am not entirely clear how it applies to your prior requirement to change the datatype of those columns.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks .. i used that one.. and its working absolutely fine. thanks a lot
0

you can generate the query as string and execute it with 'exec' keyword.

3 Comments

exec is SQL*Plus, not PL/SQL
The OP did not mention Oracle originally. A sufficiently knowledgeable person could infer it from the presence of user_tab_columns but this reply is innocent.
innocent, but not very helpful :)

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.