Create Table in a Procedure?

Hey everybody!
got a question... I would like to create a table within a procedure with a dynamic number of rows. The Input of the Procedure should be a number, and this number should determine the number of rows. Thought about something like this:
create_table(3)
-> rows: Seq_nb, Z1_Air, Z1_Gas, Z1_Time, Z2_Air, Z2_Gas, Z2_Time, Z3_Air, Z4_Gas, Z3_Time
is this possible to do? All Tries to make a CREATE TABLE within the Procedure didn't work. Also, it seems to be difficult to name a row like 'Zx_Gas', x := Number
I don't mean a temporary table, it should be a REAL table ;)
Anybody who could help me please? Thanks in advance!!

Is this the one you are trying to get?
create or replace procedure create_table(num_of_cols in number) is
num number;
stmt varchar2(400);
begin
num:=num_of_cols;
execute immediate 'drop table test_tab';
stmt:='create table test_tab(constant_cols varchar2(30)';
for i in 1.. num
loop
stmt:=stmt||', Z'||i||'_Air varchar2(30)';
stmt:=stmt||', Z'||i||'_Gas varchar2(30)';
stmt:=stmt||', Z'||i||'_Time varchar2(30)';
end loop;
stmt:=stmt||')';
execute immediate stmt;
end;

Similar Messages

  • Create table as in procedure vs SQL*Plus between 2 utf8-db's

    I have a 9.2.05 db with charset UTF8 and Polish characters in it. When I extract a table to another 9.2.05 db with UTF8 charset using create table x as selcect * ...
    When I run it in SQL*Plus everything works just fine but when I do the create table as from inside a procedure the national characters are converted to western characters and the length of the record are shorter. Why? How do I get the procedure to work as SQL*Plus does. /Göran

    This sounds strange. Could you show the code of the procedure? Could you double-check that your db link points to the right database? Could you add:
    SELECT VALUE INTO <variable1>
    FROM NLS_DATABASE_PARAMETERS
    WHERE PARAMETER='NLS_CHARACTERSET'
    SELECT VALUE INTO <variable2>
    FROM NLS_DATABASE_PARAMETERS@<dblink>
    WHERE PARAMETER='NLS_CHARACTERSET'
    to your procedure and output the contents of the PL/SQL <variable1> and <variable2>, e.g. using DBMS_OUTPUT, to verify the character sets of the databases?
    -- Sergiusz

  • How to create table in a procedure

    Dear All,
    I am new to this PLSQL.
    I want to create a table in a plsql procedure. I wrote proc but it is not working
    CREATE OR REPLACE PROCEDURE loyalty_extraction(bc VARCHAR,r VARCHAR)
    IS
    v_count NUMBER ;
    BEGIN
    EXECUTE IMMEDIATE 'CREATE TABLE' || 'R'|| r || '_bc' ||bc||'loy_batch_test' ||'AS SELECT * FROM R5_BC5_LOY_BATCH WHERE 1=2';
    EXECUTE IMMEDIATE 'SELECT COUNT(*) INTO v_count FROM R'|| r || '_bc' ||bc||'loy_batch_test';
    END;
    For Ex: If we run the proc as exec loyalty_extraction (2,2)
    output should be: a table should be created as R2_BC2_LOY_BATCH_test
    Thanks in advance.

    user9073870 wrote:
    Dear All,
    I am new to this PLSQL.
    Then add these links to your favorites to find examples and explanation regarding Oracle Database:
    http://asktom.oracle.com
    http://www.oracle.com/pls/db112/homepage
    http://www.oracle.com/pls/db102/homepage
    http://tahiti.oracle.com (all Oracle documentation)
    Creating tables on the fly (doing DDL through dynamic SQL) is usually a very bad thing to do.
    But if you insist, you could try:
    untested
    create or replace procedure loyalty_extraction(bc varchar2,r varchar2)
    is
      v_count number ;
    begin
      execute immediate 'create table '||'r'||r||'_bc'||bc||'loy_batch_test'||' as select * from r5_bc5_loy_batch where 1=2';
      execute immediate 'select count(*) from r'||r||'_bc'||bc||'loy_batch_test' into v_count ;
      dbms_output.put_line(v_count);
    end;
    /Also, when posting code, and you want it formatted, remember to use the {noformat}{noformat} tag for that.
    Put it before and after your example.
    So, when you type or paste your formatted code like this:
    {noformat}select *
    from dual;{noformat}
    it will appear as:select *
    from dual;on this forum                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Creating tables inside stored procedures

    is there a limitation as of how many tables i can cerate inside my stored proc using:
    execute immediate('CREATE TABLE xxx AS select * from yyy.... ?
    i have a stored proc that creates couple tables with the method shown above. but the compiler complains for the second create table zzz as select * from .... any idea why?
    I am attaching my procedure just in case:
    CREATE OR REPLACE
    procedure retail_cif_prep as
    begin
    begin
    execute immediate('drop table cif_retail');
    execute immediate('drop table cif_retail_wrong_ccsno');
    exception
    when others then
    null; -- or log errors other than -942 (table doesn't exist)
    end;
    execute immediate('CREATE TABLE cif_retail AS select * from cst where cstfnflag=1 and cstdatoc!=''00000000'' order by cstno');
    execute immediate('CREATE UNIQUE INDEX cif_retail_clustered ON cif_retail(CSTNO)');
    delete from cif_retail where CSTNAM='';
    execute immediate('CREATE TABLE cif_retail_wrong_ccsno AS select * from cif_retail where cstccsno not in (100, 110, 130, 900)');
    delete from cif_retail where CSTNO in (select CSTNO from if_retail_wrong_ccsno);
    end;

    Agree with 3360, this sort of things should be done beforehands.
    Basically what's happening is when you try and compile your procedure the delete statements are referencing your two tables, but I'm guessing these tables are yet to be created on the database and therefore the procedure won't compile without them.
    A dirty workaround is to put your delete statements inside execute immediate commands too.
    Then sit back, make a cup of coffee and have a good think about why on earth you are writing such poor code.

  • Creating table types for procedures at design time: Where is the "Local Table Type" tab?

    Hello,
    I want to write a stored procedure (development perspective, repository object) and need to create a table type for the result table.I am working on HANA Studio 1.80.1 and the documentation tells me that I should open the "Local Table Types" tab. However, I do not see where this tab is.
    I get an SQLScript tab nothing else. Any hints?
    Regards,
    Andreas

    Hi ,
    Have a look on this discussion:
    Table type creation via HS repository / CDS / DDl Source
    Regards,
    Krishna Tangudu

  • Writing procedure to create table

    i m trying to create table within a procedure but it is giving error
    PROCEDURE try IS
    BEGIN
    create table temp
    temp1 varchar2(10)
    END;
    is there any logic why it is not beign possible to create table in procedure

    Sorry fro posting new thread
    but i m not getting any answer which can solve the
    problem coz i m making procedure in the form and now
    i hav to create table from the form builder procedure
    and these all are not working...Just because you're stuggling to find the solution from one thread, it really doesn't help matters if you go and create a new thread with the same question.
    It's like walking into a room and asking a question, but because you don't understand the answer that people are giving you, you walk out the room and come into the same room from another door. You'll only meet the same people and get the same answers. The only difference will be that the people will be a little p'd off that you've asked the same question again.
    As APC said, create the task on the database....
    CREATE OR REPLACE PROCEDURE cre_table IS
    BEGIN
    EXECUTE IMMEDIATE ('create table ........');
    END;
    Then within forms you do....
    EXECUTE cre_table;
    ;)

  • Drop and recreate table in stored procedure

    Hi all
    When creating tables using Transact-SQL scripts, I have always preferred to drop the table if it exists and then create it explicitly using CREATE TABLE.  For two reasons:
    1) It does not matter if it is the first time the SP is run ie. if I create the table manually in the first instance and just use TRUNCATE TABLE it could fail if the table is deleted
    2) I have control over the data types of the table fields
    Just recently though I discovered the error that can occur when dropping and creating a table in the same batch (see link below)
    Microsoft Website
    This causes me a problem when dropping and creating tables in stored procedures, as I understand that a stored procedure is in itself a single batch?
    Can I avoid this error in a stored procedure whilst continuing to drop and create tables?  Or should I be taking a different approach?
    Coding best practice advice would be greatly appreciated.
    Thank you

    Thanks Ronen
    Please see my second post immediately before your reply.
    Given that I need to store the data output in a physical table for use in QlikView, would you suggest truncating the table each time the SP runs?  And then having a script that handles both dropping and creating the physical table, and also creating
    the SP?
    >> QlikView
    QlikView is an Israeli company, right?
    In any case I am not familiar with QlikView's application, therefore I can only give you general information, based on assumptions regarding the application, and facts regarding the SQL Server.
    >> for use in QlikView
    I assume that external application use specific database structure (table
    structure) and it is change only in rare situations (for example CMS interface might change the tables if and when a module s update/install). In this case there is no need to drop the table and recreate it and TRUNCATE is the solution.
    >> would you suggest truncating the table each time the SP runs
    I am sorry but i cant recommend on TRUNCATE a table each time you execute SP, without know the exact reason for this logic. It sound to me, at this point of time (with the information that we have), that this
    is very bad logic (application architecture). As I wrote above, basing your application on TRUNCATING the table each time mean that you have problems with multi users. Thins about 2 people that try to execute the same SP at almost the same time. Think about
    locking in the SQL Server and bad data (one truncate while the other already inserted the new data and get no rows, if there is no locking).
    But TRUNCATE is much better in this case probably then DROP and DELETE, since it is faster, and locking will be shorter (hopefully the application use the correct locking). There are other reasons why TRUNCATE is better, and other people already mentioned
    most of them, but time in this scenario might be critical.
    >> having a script that handles both dropping and creating the physical table, and also creating the SP?
    I do not undestand what is this second step. we said that you truncate the table, so why do you need to
    dropping and creating the physical table and who
    creating the SP?
    Are you meaning that the application create the tables and SP?
    There are lot of application that during installation create the database structure. is this what you mean?
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • Create table with timestamp

    Hello All,
    I am trying to create table within a procedure. All I am looking for is a way to create a table with timestamp (sysdate) appended to the table name.
    Below is my attempt of doing so. Can you please help me out?
    CREATE OR REPLACE PROCEDURE CREATE_TABLE1 AS
    V_SYSDATE VARCHAR2(20);
    V_TABLENAME VARCHAR2(40);
    BEGIN
    SELECT TRUNC(SYSDATE) into V_SYSDATE FROM DUAL;
    SELECT CONCAT('ORDERS_BACKUP_',V_SYSDATE) into V_TABLENAME FROM DUAL;
    EXECUTE IMMEDIATE 'CREATE TABLE ''||V_TABLENAME||'' as SELECT * from ORDERS
    END;
    Thanks,
    TT

    Despite also having concerns about your approach, maybe this is what you were looking for...
    CREATE OR REPLACE PROCEDURE CREATE_TABLE1 AS
    V_SYSDATE VARCHAR2(20);
    V_TABLENAME VARCHAR2(40);
    BEGIN
    SELECT TO_CHAR(TRUNC(SYSDATE),'DDMMYYYY') into V_SYSDATE FROM DUAL;
    SELECT CONCAT('ORDERS_BACKUP_',V_SYSDATE) into V_TABLENAME FROM DUAL;
    EXECUTE IMMEDIATE 'CREATE TABLE '||V_TABLENAME||' as SELECT * from ORDERS';
    END;Greg Pike
    http://www.singlequery.com

  • Can I create a table in a procedure submitted to job queue?

    I have created a package (with AUTHID CURRENT_USER) where some of the procedures create temporary tables to facilitate processing. These procedures run just fine when executed directly from within an anonymous block at the SQL*PLUS level. However, when I submit the procedures to the job queue (via DBMS_JOB.SUBMIT), the job is submitted successfully but fails when run. Investigating the Alert Log shows an error of insufficient privilege on the CREATE TABLE command in the procedure.
    QUESTION:
    Can I create a table from a procedure running in the Job Queue? If so, then how to get it to work? Does the job run in a different environment that needs Create Table privileges set to my schema?
    Thanks for any info you can provide.
    John

    FYI: Found the problem. In the Administrator's Guide (of course not in the supplied packages documentation about DBMS_JOB) I found:
    "How Jobs Execute
    SNP background processes execute jobs. To execute a job, the process creates a session to run the job.
    When an SNP process runs a job, the job is run in the same environment in which it was submitted and with the owner's default privileges.
    When you force a job to run using the procedure DBMS_JOB.RUN, the job is run by your user process. When your user process runs a job, it is run with your default privileges only. Privileges granted to you through roles are unavailable."
    And of course we had set up our users to get all privileges through Roles, so CREATE TABLE wasn't one of my DEFAULT PRIVILEGES!
    It sure would be nice if Oracle documentation could get its act together and provide ALL information about a topic in a logical place. The effort to find the information about privileges occurred after it took me 1/2 hour to figure out why my submissions were failing - I didn't have the ';' included in the quoted string for the procedure to be called - which I only figured out after looking at the code for DBMS_JOB where it made the note to make sure you include the ';'. Wouldn't it be good to have that MINOR DETAIL mentioned in the description of DBMS_JOB.SUBMIT?????

  • How to create tables and views and procedures in other users as one

    HI to all,
    I am having a user named vijay and i am trying to create the tables in user srini as user vijay
    in user vijay i'm having tables
    1. company
    2. department
    i wrote one procedure
    create or replace procedure sp_createobjects{short_name in varchar2}
    {my openbracket key is not working so that i put open braces here}
    as
    cursor table_name is select object_name from dba_tables where object_type = 'TABLE';
    var_table_name varchar2{1000};
    begin
    open table_name;
    loop
    fetch table_name into var_table_name;
    execute immediate 'create table ' || short_name || '.' || var_table_name || ' as select * from '||var_table_name;
    end loop;
    end;
    the procedure is created sucessfully. but when i am trying to execute the procedure it is throwing the error as insufficient privileges.
    my 2nd question is how to create the procedures into the other user?
    Thanks in advance

    First of all, your query "from dba_tables where object_type = 'TABLE'" returns all tables, not just the tables of the user vijay.
    So there are two possibilities, you may be getting the error because you cannot select from another user's table or you may be getting the error because you cannot create a table under the user srini. To create tables in another schema you need the "create any table" privilege.

  • Create table statement in a pl/sql procedure

    Hi all.
    I have a problem in Oracle 10g.
    First of all I must say that I'm new in oracle 10.
    I have a stored procedure in which I have the instruction "create table name_table as
    select col1,col2,col3,..ecc
    from table1, table2
    where table1.col1 = table2.col2"
    When I compile this procedure it gives me an error.
    Is it changed the sintax????
    Is there anyone that can help me???
    Thanks all for the collaboration,
    Fabrizio

    A little mistake -- see it --
    SQL> ed
    Wrote file afiedt.buf
      1  Create or replace procedure My_procedure as
      2  begin
      3  EXECUTE IMMEDIATE 'create table my_table(fld number(5));'
      4* end;
    SQL> /
    Warning: Procedure created with compilation errors.
    SQL>
    SQL>
    SQL> ed
    Wrote file afiedt.buf
      1  Create or replace procedure My_procedure as
      2    str varchar2(200);
      3  begin
      4   str := 'create table my_table(fld number(5))';
      5  EXECUTE IMMEDIATE(str);
      6* end;
    SQL> /
    Procedure created.
    SQL>
    SQL>
    SQL> Create or replace procedure My_procedure as
      2  begin
      3  EXECUTE IMMEDIATE 'create table my_table(fld number(5));'
      4  end;
      5  /
    Warning: Procedure created with compilation errors.
    SQL> ed
    Wrote file afiedt.buf
      1  Create or replace procedure My_procedure as
      2  begin
      3  EXECUTE IMMEDIATE 'create table my_table(fld number(5))';
      4* end;
    SQL> /
    Procedure created.Regards.
    Satyaki De.
    N.B.: Please check the bolded line. You didn't write the ; outside the quotation. Otherwise, it will compile successfully.

  • Stored procedure for creating tables

    Is it possible to create a stored procedure which only contains create tables? I prepare everything on an environment and want to transfer everything, except the data, on anothe environment. Therfore I thought of an stored procedure which does everything automatically. Additional I want to create a package which contains all necessary stored procedures (which are already finished). Is it better to insert the create-table-lines in the package?
    Thanks for your help!

    PL/SQL is not the appropriate tool for this.
    What does Oracle RDBMS products like Apex use to install? SQL*Plus scripts. A combination of SQL code and anonymous PL/SQL blocks.
    This is also what we use to install any one of a dozen Oracle systems we have developed.. it is as simple as running 'sqlplus "/ as sysdba" @installer <tablespace> <schema> <password>'.
    Trying to do this type of thing in PL/SQL... lots of disadvantages, lots of complexities, and very little (if any) benefit.

  • How to create views or table in a procedure?

    I 'd like to create a procedure that will automatically create a view or a table
    but Oracle seem not allow me to do this. Could someone help me please.

    Hi,
    You cannot use DDL, like CREATE, ALTER, etc., in PL/SQL code.
    To do that You have to use dynamic strings.
    For example
    DECLARE
       v_Din_Sql VARCHAR2(32767);
    BEGIN
       v_Din_Sql := 'CREATE TABLE MyTab (MyField NUMBER)';
       EXECUTE IMMEDIATE v_Din_Sql;
    END;
    /Hop this helps
    Max

  • Create table statement in stored procedures

    Hi,
    I am including the following statement in a stored procedure and receive the following error:
    STATEMENT:
    create table wrk_date (date date,
    qty smallint)
    tablespace temptabs;
    ERROR:
    PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:
    begin declare exit for goto if loop mod null pragma raise
    return select update while <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> <<
    close current delete fetch lock insert open rollback
    savepoint set sql commit <a single-quoted SQL string>
    Is this statement not allowed or is there a possible syntax error above?
    I am using Oracle database version 8.0.5.
    Thanks.
    null

    Jimmy - You might want to buy the Following book from Oreilley Press Oracle Built in Pacakages it's very very good and came in handy when I has to write dynamic SQL (DBMS_SQL package).
    You might want to try www.bookpool.com which has technical books cheaper than amazon.
    Hope this helps.
    _Satish
    Oracle 8 Certified D.B.A.
    Sun Certified Sysadmin

  • Select count into versus create table as in functions/procedures

    I am working on a dynamic PL/SQL script that will count the number of records in a remote database
    based on certain criteria and then if the number is "acceptable" will create a table in the connecting
    database with those records.
    My where clauses are supposed to be the same but I am presented with the problem, when I run the
    first code ... select in to rowcount I get 122000 records, when I later do the create table as
    with the same whereclause code, I get 77 records. So now I am attempting to validate that the two
    where clauses are the same ... you'd think it would be obvious, but it's not.
    My first operation does a select count(*) into rowcount with the where clause behind it.
    The second operations creates a "sql command literal' that gets executed and returns the less value.
    I build it like testscript := 'create table '||tablename ||'as select * from '||remotetablename||'@'||linkname;
    testwhere := ' xxxxxxx'
    then I do an execute immediate teststring ||' ' testwhere; which works but gives me 77 rows in the table.
    Since I believe my where clause might be different, how can I run the first operation ... select count into rowcount
    as a normal SQL statement in the script...
    When I attempt to just run it I get -- PLS-00428: an into clause expected in this select statement......
    I will provide the source code in my next posting. Working to get it moved to this system.. Once you see it you'll understand
    why I don't think, it's the same, but I need a way to run them exactly as they are written to understand the different results.
    so How can I make the select count (*) into rowcount from .... work just like a normal select

    Here is first part of the procedure --- I get returned value of 122000 records ....
    SELECT COUNT (*)
                   INTO ROWCOUNT
                   FROM A_K_A_D_TBL@FCA08_INGRES
                   WHERE (( "a_" = '1' OR "a_" = '6' ) AND
                             ( "d_t" <> '3' OR "k_c_s" = 'Y' ) AND
                             "d_d" < DATECUTOFFDATE AND
                        "k_c_d" < DATECUTOFFDATE )OR
    (( "a_" = 4 OR "a_" = 7 ) AND
                             ( "d_t" <> '3' OR
    "k_c_s" = 'Y' OR
    "r_t" = '0' OR
                        "r_t" = '2' OR
                   "r_t" = '3' ) AND
                        "d_d" < DATECUTOFFDATE AND
                        "k_c_d" < DATECUTOFFDATE AND
                        "r_d" < DATECUTOFFDATE AND
                        "s_d" < DATECUTOFFDATE);
    then I attempt to duplicate it for string literals.... when this runs ... I get only 77 records. So that makes me think that my strings are not
    done properly.
    So I want to try to run the first sql itself ... but then I get the errors about needing select into ..... etc..
                   TESTWHERE := q'[WHERE (( "a_" = '1' OR "a_" = '6' ) AND ( "d_t" <> '3' OR "k_c_s" = 'Y' )]'||
              q'[ AND "d_d" < DATE ']'||TO_CHAR(DATECUTOFFDATE,'YYYY-MM-DD')||q'[']'||
                             q'[ AND "k_c_d" < DATE ']'||TO_CHAR(DATECUTOFFDATE,'YYYY-MM-DD')||q'[')]'||
                             q'[ OR (( "a_" = 4 OR "a_" = 7 )]'||
                             q'[ AND ( "d_t" <> '3' OR "k_c_s" = 'Y' OR "r_t" = '0' OR "r_t" = '2' OR "r_t" = '3' )]'||
                             q'[ AND "d_d" < DATE ']'||TO_CHAR(DATECUTOFFDATE,'YYYY-MM-DD')||q'[']'||
                             q'[ AND "k_c_d" < DATE ']'||TO_CHAR(DATECUTOFFDATE,'YYYY-MM-DD')||q'[']'||
                             q'[ AND "r_d" < DATE ']'||TO_CHAR(DATECUTOFFDATE,'YYYY-MM-DD')||q'[']'||
                             q'[ AND "s_d" < DATE ']'||TO_CHAR(DATECUTOFFDATE,'YYYY-MM-DD')||q'[')]';
                        TESTSTRING := 'CREATE TABLE '||UCASEXTABLENAMETEMP||' AS SELECT * FROM '||UCASEXTABLENAME||'@'||XLINKNAME;
                        DBMS_OUTPUT.PUT_LINE(TESTSTRING);
                        DBMS_OUTPUT.PUT_LINE(TESTWHERE);
                        EXECUTE IMMEDIATE TESTSTRING||' '||TESTWHERE;

Maybe you are looking for