ALTER TABLE privilege and CREATE/DROP/ENABLE/DISABLE constraint privilege

Hi,
I am looking for some detailed info regarding the below previleges
ALTER TABLE, CREATE CONSTRAINT, DROP CONSTRAINT, ENABLE CONSTRAINT AND DISABLE CONSTRAINT PRiVILEGES.
I have two schemas 'A' and 'B', I want to provide user 'A' with Alter table, create or drop constraint,Enable or Disable constraint on schema B.
Please let me know how to make this work.
Thank you

I got the answer for my second question, I have an option to grant 'Alter ANY table' privilege to the user.Yes, but you should not do that.
Regarding question one, Suppose I have two schemas A and B and I want Schema A to have alter table privilege on all tables of Schema B.
Can I do this in one command No
or I need to grant alter on each table saperately?Yes
If I am chosing the second option for each table saperately then whenever a table is added in schema B we need to grant privilege on that table as well.Yes. But nothing strange there. Designing and creating objects includes the privileges on them.
If user A is granted with alter table privilege on a table which user B owns then can user A drop/create/enable/disable constraints for that table?Yes, isn't that what all this about?
Again, letting one user alter the objects of another user is generally not such a good idea. Hope you see this from our discussion.
Alter table privilege includes adding and dropping columns. This is why I suggested writing a procedure that does exactly what you need. And then grant execute on that to A.
The best thing of course would be NOT TO disable the constraints, they are probably there for a reason.
I am currently handling an issue where one session doing this, deadlocks with another session doing only selects - From other tables, that is!
Regards
Peter

Similar Messages

  • Enable/disable constraint

    Hi!
    Kindly help.
    I'm using 9207 on win server 2k3.
    I have a master table with 100M records, I need to retain only 10M of data. I plan to put the 10M of data to be retained to a temp table, I truncate the master table, then I put the 10M of data from the temp table back to the master table. I will use the parallel and nologging for the index and table and I'll use the skip_unusable_index option. Is it ok to disable the constraints? After the bulk load I'll still be able to enable them correct?
    I'm just worrying that I might not be able to enable the constraints.
    Thanks and Best REgards
    Dexter

    You can disable the constraints before the operation and enable them afterwards. It will not be a problem unless you insert invalid data not matching your constraints.
    You can insert the rows you want into a new table, create indexes and constraints and then rename that table. This way you do not need to reinsert the rows back to the original table from the temp table.

  • What happens to Existing index after table partition and created with local index

    Hi guys,
    desc part id  number, name  varchar2(100), salary  number
    In an existing table  PART  i am  adding 1 more column DATASEQ NUMBER. i am asked to partition the table part based on dataseq.now the table is created with this logic
    create table part( id  number, name  varchar2(100), salary  number, DATASEQ  number) partition by list(dataseq) (partition PART_INITIAL  values (1));
    Suggestionn required. since  the table is partitioned based on DATASEQ i am asked to add local index on dataseq. i have added local index to dataseq create index idx on part(dataseq) LOCAL; Now my question is  already there is existing index is for the column ID and salary.
    1)  IDX for  dataseq is created locally so that it will have partition on each partition on the main table. Please tell me what happens to the existing index on the column ID and salary.. will it again created in local?
    Please suggest
    S

    Hi,
    first of all, in reality "partition a table" means create a new table a migrate existing data there (although theoretically you can use dbms_redefinition to partition an existing table -- however, it's just doing the same thing behind the scenes). This means that you also get to decide what to do with the indexes -- which indexes will be local, which will be global (you can also re-evaluate some of existing indexes and decide that they're not really needed).
    Second of all, the choice of partitioning key looks odd. Partitioning is a data manageability technique more than anything else, so in order to benefit from it you need to find a good partitioning key. A recently added column named "data_seq" doesn't look like a good candidate. Can you provide more details about this column and why it was chosen as a partitioning key?
    I suspect that whoever suggested this partitioning scheme is making a huge mistake. A non-partitioned table is much better in all aspects (including manageability and performance) than wrongly partitioned one.
    Best regards,
    Nikolay

  • Custom Infotype : Only for Disply Mode Change and Create Should be disable

    Dear Experts,
                        I Created a custom infotype in PM01 for Exit process , my client requirement is this infotype  only shows the details .
    Could you please tell me how to disable the Create and change button in PA30 Screen ?
    Regards,
    Sivakumar.A

    hi siva
    In PM01 itself you have option module pool, select that option go to screen program.
    there select field->dbl clk-> screen attributes pop up will come.
    there you have to change the input/output option
    Regards
    Deva

  • Disabling constraints

    HI,
    Is there a way in oracle 10g to disable all constraints using a single query?If yes,what is it?
    Thanks in advance

    Here is a generic script that will turn off all FKs for MY_SCHEMA. It is easy enough to adapt to more than one schema, more than one constraint type, and etc. Just be careful not to mess with SYS, SYSTEM, and other Oracle supplied schemas.
    set serveroutput on
    BEGIN
      dbms_output.enable(1000000);
        FOR x IN ( SELECT owner,
                          table_name,
                          constraint_name
                     FROM dba_constraints
                    WHERE owner IN ( 'MY_SCHEMA' )
                      AND constraint_type = 'R'
                      AND status          = 'ENABLED')
        LOOP
          BEGIN
            EXECUTE IMMEDIATE 'alter table '||x.owner||'.'||x.table_name||' disable constraint ' ||
                              x.constraint_name;
    --      EXCEPTION
    --        WHEN others THEN
    --              NULL;
    --          dbms_output.put_line('Bad owner = '||x.owner||';  Bad table_name='||x.table_name||
    --                               ';  Bad constraint_name='||x.constraint_name);
          END;
        END LOOP;
    END;
    /

  • How to enable /disable a command Button based on a table's selectOne choice

    Hi everyone.
    I am using JDeveloper 10.1.3.3 and wish to enable / disable a commandButton based on the user's selection of the selectOne radio button.
    The idea is that a row of a table may have an associated document so I want to enable or disable the button that downloads it based n the current row selected.
    I have followed the advice on problem with table I defined my selectOne component as follows :
    <af:tableSelectOne text="#{res['tables.selectionFacet.title']}"
        autoSubmit="true"
        attributeChangeListener="#{backing_browseCVs.onSelectionChange}">The function inside the backing bean looks like this
        public void onSelectionChange(AttributeChangeEvent attributeChangeEvent)
            // access the faces context
            FacesContext fc = FacesContext.getCurrentInstance();
            // get value of the expression #{row.hasCVDocument} that indicates
            // if a document has been added
            ValueBinding vb =
                fc.getApplication().createValueBinding("#{row.hasCVDocument}");
            Boolean hasDoc = (Boolean)vb.getValue(fc);
            // enable the doownload button accordingly
            downloadCVDocBtn.setDisabled(!hasDoc);
        }My problem is that the method never fires. I have placed a breakpoint at the first line but it is never reached.
    Any advice will be most welcome.
    Thanassis

    Hi,
    You might need to add 'dataProvider' part in the expression language in your selectionListener:
    #{bindings.CVList.currentRow.[b]dataProvider.hasCVDocument}
    #{bindings.CVList.currentRow} returns an instance of ViewRowImpl which does not have 'getHasCVDocument()' method, but does have:
    Object getCurrentRow()
    method, which returns objects from your CVList list, which do have getHasCVDocument() method...
    Expression language is resolved through reflection, so when you write:
    #{processScope.someClass.someReferencedClass.someAttribute} it is something like:
    Get someClass from processScope map, then:
    someClass.getSomeReferencedClass().getSomeAttribute()
    It's a bit more complex but you get the idea.
    Vladimir

  • From SQLDev2.1 and on... Disable Constraint Bug

    Hi everyone,
    Since SQLDeveloper 2.0 there's a bug in the query generated by the software when you right click a table > constraint > Disable all related constraints
    It generates the following:
    begin
                                  for cur in (select fk.owner, fk.constraint_name , fk.table_name
                                       from all_constraints fk, all_constraints pk
                                       where fk.CONSTRAINT_TYPE = 'R' and
                                       pk.owner = 'OWNER' and
                                       fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME and
                                       pk.TABLE_NAME = 'TABLE_NAME') loop
                                  execute immediate 'ALTER TABLE '||cur.owner||'.'||cur.table_name||' MODIFY CONSTRAINT '||'''cur.constraint_name'''||' DISABLE';
                             end loop;
                             end;
    when it should be:
    begin
                                  for cur in (select fk.owner, fk.constraint_name , fk.table_name
                                       from all_constraints fk, all_constraints pk
                                       where fk.CONSTRAINT_TYPE = 'R' and
                                       pk.owner = 'OWNER' and
                                       fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME and
                                       pk.TABLE_NAME = 'TABLE_NAME') loop
                                  execute immediate 'ALTER TABLE '||cur.owner||'.'||cur.table_name||' MODIFY CONSTRAINT '||cur.constraint_name||' DISABLE';
                             end loop;
                             end;
    [The problem is on cur.constraint_name]
    On the new SQLDeveloper 3.0 EA4 this bug its still valid...
    To enable the constraint is ok.
    Has anyone else seen this?

    Hey,
    I've tested out the disable constraints script generation on 3.1 EA1 [3.1.05.97] and now it creates the script just fine. Also with the 'fk.r_owner = pk.owner' part that was missing.
    The generated script:
    begin
                                  for cur in (select fk.owner, fk.constraint_name , fk.table_name
                                       from all_constraints fk, all_constraints pk
                                       where fk.CONSTRAINT_TYPE = 'R' and
                                       pk.owner = 'TEST_OWNER' and
                  fk.r_owner = pk.owner AND
                                       fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME and
                                       pk.TABLE_NAME = 'TEST_TABLE') loop
                                    execute immediate 'ALTER TABLE "'||cur.owner||'"."'||cur.table_name||'" MODIFY CONSTRAINT "'||cur.constraint_name||'" DISABLE';
                                end loop;
                             end;My thanks to everybody of the SQL Developer Team.

  • Recreating foreign key not working? two proc one to drop constraint and another to recreate foreign constraint in database?

    CREATE PROC [dbo].[SP_DropForeignKeys] 
    AS
    BEGIN
    DECLARE @FKTABLE_OWNER SYSNAME, @FKTABLE_NAME sysname, @FK_Name sysname
    DECLARE Cursor_DisableForeignKey CURSOR FOR  
    SELECT   schema_name(schema_id), object_name(parent_object_id), name
    FROM   sys.foreign_keys
    OPEN Cursor_DisableForeignKey
    FETCH NEXT FROM   Cursor_DisableForeignKey  
    INTO  @FKTABLE_OWNER  , @FKTABLE_NAME, @FK_Name 
    DECLARE @SQL nvarchar(max)
    WHILE @@FETCH_STATUS = 0   
    BEGIN  
    SET @SQL  = 'ALTER TABLE [' + @FKTABLE_OWNER + '].[' + @FKTABLE_NAME   
               + ']  DROP CONSTRAINT [' + @FK_NAME + ']'  
    select @sql
    EXECUTE (@SQL)
    FETCH NEXT FROM   Cursor_DisableForeignKey INTO @FKTABLE_OWNER, @FKTABLE_NAME, @FK_Name
    END  
    CLOSE Cursor_DisableForeignKey
    DEALLOCATE Cursor_DisableForeignKey
    END
    create proc [dbo].[SP_CreateForeignKeys]
    as
    DECLARE @schema_name sysname;
    DECLARE @table_name sysname;
    DECLARE @constraint_name sysname;
    DECLARE @constraint_object_id int;
    DECLARE @referenced_object_name sysname;
    DECLARE @is_disabled bit;
    DECLARE @is_not_for_replication bit;
    DECLARE @is_not_trusted bit;
    DECLARE @delete_referential_action tinyint;
    DECLARE @update_referential_action tinyint;
    DECLARE @tsql nvarchar(4000);
    DECLARE @tsql2 nvarchar(4000);
    DECLARE @fkCol sysname;
    DECLARE @pkCol sysname;
    DECLARE @col1 bit;
    DECLARE @action char(6);
    SET @action = 'CREATE';
    DECLARE FKcursor CURSOR FOR
        select OBJECT_SCHEMA_NAME(parent_object_id)
             , OBJECT_NAME(parent_object_id), name, OBJECT_NAME(referenced_object_id)
             , object_id
             , is_disabled, is_not_for_replication, is_not_trusted
             , delete_referential_action, update_referential_action
        from sys.foreign_keys
        order by 1,2;
    OPEN FKcursor;
    FETCH NEXT FROM FKcursor INTO @schema_name, @table_name, @constraint_name
        , @referenced_object_name, @constraint_object_id
        , @is_disabled, @is_not_for_replication, @is_not_trusted
        , @delete_referential_action, @update_referential_action;
    WHILE @@FETCH_STATUS = 0
    BEGIN
              BEGIN
            SET @tsql = 'ALTER TABLE '
                      + QUOTENAME(@schema_name) + '.' + QUOTENAME(@table_name)
                      + CASE @is_not_trusted
                            WHEN 0 THEN ' WITH CHECK '
                            ELSE ' WITH NOCHECK '
                        END
                      + ' ADD CONSTRAINT ' + QUOTENAME(@constraint_name)
                      + ' FOREIGN KEY ('
            SET @tsql2 = '';
            DECLARE ColumnCursor CURSOR FOR
                select COL_NAME(fk.parent_object_id, fkc.parent_column_id)
                     , COL_NAME(fk.referenced_object_id, fkc.referenced_column_id)
                from sys.foreign_keys fk
                inner join sys.foreign_key_columns fkc
                on fk.object_id = fkc.constraint_object_id
                where fkc.constraint_object_id = @constraint_object_id
                order by fkc.constraint_column_id;
            OPEN ColumnCursor;
            SET @col1 = 1;
            FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
            WHILE @@FETCH_STATUS = 0
            BEGIN
                IF (@col1 = 1)
                    SET @col1 = 0
                ELSE
                BEGIN
                    SET @tsql = @tsql + ',';
                    SET @tsql2 = @tsql2 + ',';
                END;
                SET @tsql = @tsql + QUOTENAME(@fkCol);
                SET @tsql2 = @tsql2 + QUOTENAME(@pkCol);
                FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
            END;
            CLOSE ColumnCursor;
            DEALLOCATE ColumnCursor;
            SET @tsql = @tsql + ' ) REFERENCES ' + QUOTENAME(@schema_name) + '.' + QUOTENAME(@referenced_object_name)
                      + ' (' + @tsql2 + ')';           
            SET @tsql = @tsql
                      + ' ON UPDATE ' + CASE @update_referential_action
                                            WHEN 0 THEN 'NO ACTION '
                                            WHEN 1 THEN 'CASCADE '
                                            WHEN 2 THEN 'SET NULL '
                                            ELSE 'SET DEFAULT '
                                        END
                      + ' ON DELETE ' + CASE @delete_referential_action
                                            WHEN 0 THEN 'NO ACTION '
                                            WHEN 1 THEN 'CASCADE '
                                            WHEN 2 THEN 'SET NULL '
                                            ELSE 'SET DEFAULT '
                                        END
                      + CASE @is_not_for_replication
                            WHEN 1 THEN ' NOT FOR REPLICATION '
                            ELSE ''
                        END
                      + ';';
            END;
        PRINT @tsql;
        IF @action = 'CREATE'
            BEGIN
            SET @tsql = 'ALTER TABLE '
                      + QUOTENAME(@schema_name) + '.' + QUOTENAME(@table_name)
                      + CASE @is_disabled
                            WHEN 0 THEN ' CHECK '
                            ELSE ' NOCHECK '
                        END
                      + 'CONSTRAINT ' + QUOTENAME(@constraint_name)
                      + ';';
            PRINT @tsql;
            END;
        FETCH NEXT FROM FKcursor INTO @schema_name, @table_name, @constraint_name
            , @referenced_object_name, @constraint_object_id
            , @is_disabled, @is_not_for_replication, @is_not_trusted
            , @delete_referential_action, @update_referential_action;
    END;
    CLOSE FKcursor;
    DEALLOCATE FKcursor;
    GO
    exec [dbo].[SP_DropForeignKeys] 
    exec [dbo].[SP_CreateForeignKeys]
    droped proc worked perfect but when i execute [dbo].[SP_CreateForeignKeys] and try to see again foreign key constraints but result is empty?
    can anybody suggest me what's wrong with these script?

    droped proc worked perfect but when i execute [dbo].[SP_CreateForeignKeys] and try to see again foreign key constraints but result is empty?
    Well, if you have dropped the keys, you have dropped them. They can't be recreated out of the blue. You need to use modify procedure to save the ALTER TABLE statements in a temp table, drop the keys, truncate the tables, and the run a cursor over the
    temp table. In a single transaction, so that you don't lose the keys if the server crashes half-way through.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Problem with alter table in execute immediate

    We have PL/SQL scripts which modify the data structure, add data etc to en existing database. These scripts basically ensure that the db is compatible with what the software expects.
    The reason for doing it in PL/SQL rather than SQL script is A) The scripts are launched using GUI so that they are more user friendly. sqlplus is launched as a background process which executes these scripts. All the scripts have EXIT FAILURE WHENEVER SQLERROR as first line to ensure that the control does not hang in the sqlplus background process.
    Going from one version to other, we have added a few tables to the database and also modified a few tables. since (i think) DDL is not allowed in PL/SQL block, we had to resort to putting them in EXECUTE IMMEDIATE enclosures.
    Now for the real question,
    If I create a table using EXECUTE IMMEDIATE clause, I can immediately have insert as a next statement to insert data in this table. but, if I alter the table and add a column to the existing table, I cannot immediately add data to that column, it throws an error saying 'invalid identifier'
    At code level, the following is allowed :
    EXECUTE IMMEDIATE 'CREATE TABLE SP_TEST_TABLE
                             ID     NUMBER,
                             NAME     Varchar2(40)
    INSERT INTO SP_TEST_TABLE(ID, NAME) Values(1, 'SP');
    but I get error for the following :
    EXECUTE IMMEDIATE 'ALTER TABLE SP_TEST_TWO ADD
                        ANOTHER_COLUMN     number
    UPDATE     SP_TEST_TWO SET          ANOTHER_COLUMN = 1;
    In this case, it says ANOTHER_COLUMN invalid identifier
    Does anybody know why?
    any workaround will be greatly appreciated.
    --SP                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Friends,
    Thanks to all of you for your help. The spelling mistakes might have occurred becuase i changed the actual script to something 'short and complete' to show the problem.
    I could solve the problem by having more than one PL/SQL block within my file. something like :
    BEGIN
    --alter table statements here
    END;
    BEGIN
    --insert the values in column here.
    END;
    I am still not sure why the error is presented only on alter table statement and not for create table statement. Probably somebody with the knowledge of oracle internals will be able to throw more light on it. I am trying to get the naswers, if I get the answer, I'll surely post it here.
    Regards,
    --Saurabh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Alter Table problem

    Hi there. I'm new in Oracle environments. I've a problem with this procedure with the alter table statement.
    CREATE OR REPLACE PROCEDURE HR.PROC_ETL_TAB IS
    CURSOR cursor_ETL IS
    SELECT * FROM ETL_TAB_REF WHERE AVAILABLE_FLAG = 1;
    record_etl ETL_TAB_REF%ROWTYPE;
    VAR_ALTER VARCHAR2(100);
    BEGIN
    OPEN cursor_ETL;
    LOOP
    FETCH cursor_ETL INTO record_etl;
    EXIT WHEN cursor_ETL%NOTFOUND;
    VAR_ALTER:='ALTER TABLE '||record_etl.EXT_TABLE_NAME||' LOCATION('''||record_etl.FILE_NAME||''')';
    DBMS_OUTPUT.PUT_LINE(VAR_ALTER);
    EXECUTE IMMEDIATE VAR_ALTER;
    END LOOP;
    CLOSE cursor_ETL;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    NULL;
    WHEN OTHERS THEN
    -- Consider logging the error and then re-raise
    RAISE;
    END PROC_ETL_TAB;
    When I try to call the procedure (call proc_etl_tab()) this error occurs: ORA-01735: invalid ALTER TABLE option. Can anyone help me please? Thanks.

    Pl post details of OS and database versions, along with a sample of what this command would look like when the variables are evaluated
    VAR_ALTER:='ALTER TABLE '||record_etl.EXT_TABLE_NAME||' LOCATION('''||record_etl.FILE_NAME||''')';
    I do not believe ALTER TABLE ... LOCATION ... is a valid command.
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_3001.htm
    HTH
    Srini

  • Cannot ALTER TABLE

    I cannot alter tables that I created, add and modify give me a
    syntax error. How can this be? Does anyone have anything
    positive to say about Personal Oracle Lite?
    null

    Ranga Rao (guest) wrote:
    : David Kachuck (guest) wrote:
    : : I cannot alter tables that I created, add and modify give me
    a
    : : syntax error. How can this be? Does anyone have anything
    : : positive to say about Personal Oracle Lite?
    : Mr David,
    : Please give me details about the problem and what exactly the
    : message is?
    : --Ranga Rao V.
    1 alter table title_copy
    2* modify (customer varchar2(30));
    SQL> /
    alter table title_copy
    ERROR at line 1:
    OCA-30021: error preparing/executing SQL statement
    [POL-5228] syntax error
    null

  • Alter  Table 's Tablespace

    Dear All ,
    I have 10g database on rehl5 .I move table's(T_TRANSACTION_TABLE) tablespace(USERS) to tablespace (IMAGES) .
    It completed successfully
    MY command is
    ALTER TABLE USERS MOVE TABLESPACE IMAGES
    and
    ALTER INDEX USERS REBUILD TABLESPACE IMAGES
    Problem is transaction_images table show using table space IMAGES but store data in USERS table space .
    I check this using em->administrator->schema->Table
    and i also check DBA_SEGMENT,DBA_EXTENTS both are show tablespace USERS
    Note :- 1) This table contain BLOB column for save image .
    2) I am also rebuild index also.
    Thanks in advance
    Shaikh Abdul Moyed

    A LOB (CLOB or BLOB) can be stored in a different tablespace than the rest of the table. Are you certain that you're looking at the tablespace for the table segment rather than the LOB segment?
    If you want to move the LOB segment to a different tablespace
    ALTER TABLE <<table name>>
      MOVE LOB( <<name of BLOB column>> )
      STORE AS( TABLESPACE <<new tablespace>> )Additionally, I'm a bit confused by the DDL you posted
    ALTER TABLE USERS MOVE TABLESPACE IMAGES
    ALTER INDEX USERS REBUILD TABLESPACE IMAGESYou use USERS as a table name and as an index name in these DDL statements. But then you later talk about the USERS tablespace. I'm guessing that you really put the table name (TRANSACTION_IMAGES) in the ALTER TABLE command and that you used the correct index name in your ALTER INDEX.
    Justin

  • Basic anonymous block which drops and creates a table

    Version: 11.2.0.3
    I am fairly new to PL/SQL.
    We have a table named CHK_CNFG_DTL.
    I want to create a backup table for CHK_CNFG_DTL which will be named like CHK_CNFG_DTL_BKP_<timestamp> eg: CHK_CNFG_DTL_BKP_JULY_22_2013
    Creation of this backup table has to be automated so, I want to create an anonymous block which will first drop the existing backup table and then create a new backup table from the original table.
    The below code works fine. But the very first time when you run it , the loop won't iterate because there is no such table named CHK_CNFG_DTL_BKP%.
    declare
    v_stmt varchar2(1000);
    v_date date;
    begin
      for rec in
      (select * from user_tables where table_name like 'CHK_CNFG_DTL_BKP%' )
        loop
            begin
                execute immediate 'alter session set nls_date_format=''DD_MON_YYYY''';
                v_stmt := 'drop table '||rec.table_name|| ' purge';
                dbms_output.put_line(v_stmt);   ----- Drops Old backup table
                execute immediate v_stmt;
                select sysdate into v_date from dual;
                v_stmt := 'create table CHK_CNFG_DTL_BKP_'||to_date(v_date)||' as select * from CHK_CNFG_DTL';
                dbms_output.put_line('Creating Bkp table CHK_CNFG_DTL_BKP_'|| to_date(v_date) );
                dbms_output.put_line(v_stmt);
                execute immediate v_stmt;  --- Creates new Backup table
            exception
            when others
            then
            dbms_output.PUT_LINE (rec.table_name||'-'||sqlerrm);
            end;
        end loop;
    end;
    PL/SQL procedure successfully completed.
    -- Backup table not created.
    SQL> select table_name from user_Tables where table_name like 'CHK_CNFG_DTL%';
    TABLE_NAME
    CHK_CNFG_DTL
    Of course, this can fixed by creating a table like bleow before executing the anonymous block
    SQL> create table CHK_CNFG_DTL_BKP_JULY_22_2013 (x varchar2(37));
    Table created.
    and now the block will succesfully run like
    24  end;
    25  /
    drop table CHK_CNFG_DTL_BKP_JULY_22_2013 purge
    Creating Bkp table CHK_CNFG_DTL_BKP_22_JUL_2013
    create table CHK_CNFG_DTL_BKP_22_JUL_2013 as select * from CHK_CNFG_DTL
    PL/SQL procedure successfully completed.
    But this is going to production . We can't a table like CHK_CNFG_DTL_BKP_JULY_22_2013 without a proper business reason.
    How can I modify the above code so that if even if there is no such table like 'CHK_CNFG_DTL_BKP%' , it will proceed to create the backup table?

    Hi,
    Why won't you push the creation of the backup out of the loop ?
    declare
    v_stmt varchar2(1000);
    v_date date;
    begin
      for rec in
      (select * from user_tables where table_name like 'CHK_CNFG_DTL_BKP%' )
        loop
            begin
                execute immediate 'alter session set nls_date_format=''DD_MON_YYYY''';
                v_stmt := 'drop table '||rec.table_name|| ' purge';
                dbms_output.put_line(v_stmt);   ----- Drops Old backup table
                execute immediate v_stmt;
            exception
            when others
            then
            dbms_output.PUT_LINE (rec.table_name||'-'||sqlerrm);
            end;
        end loop;
                select sysdate into v_date from dual;
                v_stmt := 'create table CHK_CNFG_DTL_BKP_'||to_date(v_date)||' as select * from CHK_CNFG_DTL';
                dbms_output.put_line('Creating Bkp table CHK_CNFG_DTL_BKP_'|| to_date(v_date) );
                dbms_output.put_line(v_stmt);
                execute immediate v_stmt;  --- Creates new Backup table
    end;

  • ALTER TABLE vs DROP/CREATE statements

    Hello Everyone,
    I have created a script in order to update our database which includes adding new columns to a table. However, database changes and script generation must now be done using the Erwin data modeler and script generated using a compare option (within Erwin) which compares the model with the actual database.
    I had a script of a few lines with a few ALTER TABLE ...ADD COLUMN statements to add the new columns.
    Now, in Erwin, instead of generating 'ALTER TABLE...ADD COLUMN statements, Erwin has generated an ALTER TABLE...RENAME and CREATE TABLE statements which as a side effect will drop/re-create the table, all of it's indexes, constraints, foreign keys, etc.
    Instead of a few simple "hand written" lines to run a fast script, the script is a few pages long with all of those DROP/CREATE statements, which makes the script way too much complicated and takes much longer to run.
    And this, even though the Erwin option "USE ALTER TABLE ADD COLUMN" statement to create columns.
    I was told that the DROP/CREATE is normal and that this is the way it should be done.
    Am I out of it by thinking that it should use ALTER TABLE ADD COLUMN statements to add new columns to a table and not the DROP/CREATE methodology ? Am I missing something ? Do these new "data thinkers" know something that I am missing ?
    Makes me think of the 80s when people were generating dBase application with the included application generator and were ending up with all kinds of useless and non efficient code.
    Any though on this ? Am I out in the field ?
    Thank you.

    Thank you both for your replies.
    Neil,
    I didn't think that adding new blank columns using the ALTER TABLE ADD COLUMN statement would make the table more fragmented than it already was to begin with.
    I would have think that this kind of maintenance would take place on it's own, outside of a new deployment release.
    I have always used the ALTER TABLE ADD COLUMN instead of the DROP/CREATE TABLE statements to add new columns to a table because of the simplicity, speed and lower risk involved compare to dropping a table and all of it's objects then re-create all of them and doing an import.
    What do any of you do when you need to add new columns to a table ? Use the drop table and re-create or the ALTER TABLE ADD COLUMN ?
    Any comments welcome.
    Thanks again.

  • How to create stored procedure to drop and create table

    Version: Oracle 10g
    I am trying to create a stored procedure that will drop and create a table based on a select statement. I can create the table but I can't drop it.
    CREATE OR REPLACE procedure EC_LOAD is
    begin
    INSERT INTO Sales_table
    (FSCL_WK,
    DIV,
    ACCT_TYPE)
    Select
    FSCL_WK,
    DIV,
    ACCT_TYPE
    from
    sales_revenue;
    end ecload;
    I need to drop Sales_table before inserting the values. How do i do this?

    Or with a drop:
    SQL> desc emp2
    ERROR:
    ORA-04043: object emp2 does not exist
    SQL>
    SQL> declare
      2    cnt      int := 0;
      3  begin
      4    select max (1)
      5      into cnt
      6      from user_tables
      7     where table_name = 'EMP2';
      8
      9    if cnt = 1
    10    then
    11      execute immediate 'drop table emp2';
    12    end if;
    13
    14    execute immediate 'create table emp2 as select * from emp';
    15  end;
    16  /
    PL/SQL procedure successfully completed.
    SQL>
    SQL> desc emp2
    Name                                      Null?    Type
    EMPNO                                              NUMBER(4)
    ENAME                                              VARCHAR2(10)
    JOB                                                VARCHAR2(9)
    MGR                                                NUMBER(4)
    HIREDATE                                           DATE
    SAL                                                NUMBER(7,2)
    COMM                                               NUMBER(7,2)
    DEPTNO                                             NUMBER(2)
    SQL>

Maybe you are looking for