`
ihyperwin
  • 浏览: 424943 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

DB2中 ALTER TABLE为什么需要 REORG操作

阅读更多
ALTER TABLE操作在日常开发中很常见,下面是摘自DB2官网关于ALTER TABLE操作的一段话

Perhaps the most important thing to realize when running an ALTER TABLE statement containing a REORG-recommended operation is that once the ALTER TABLE statement has executed, the table will be placed in the Reorg Pending state. This means that the table is inaccessible for almost all operations until you perform a REORG. See the ALTER TABLE statement in the SQL Referencefor the complete list of ALTER TABLE operations, some of which are also called REORG-recommended operations.


简单地说就是运行ALTER TABLE时要注意当前运行的语句是否需要执行REORG操作,对于这样的ALTER TABLE语句,如果不执行REORG操作的话,基本上目标表就不再可用。至于什么样的语句需要REORG,什么样的不需要,看SQL Reference去!下面是一个具体的例子演示:

CREATE TABLE my_test AS (
    SELECT id,
       ...
       sla_priority1_time,
       sla_priority2_time,
       sla_priority3_time,
       sla_priority4_time,
       CAST(NULL AS DECIMAL(11, 2)) AS approvedDouAmount,
       CAST(NULL AS DECIMAL(4)) AS year
      FROM fin_attributes
)
WITH NO DATA;

ALTER TABLE my_test ALTER COLUMN id SET GENERATED ALWAYS AS IDENTITY;
ALTER TABLE my_test ADD COLUMN datetime TIMESTAMP NOT NULL GENERATED BY DEFAULT FOR EACH ROW ON UPDATE AS ROW CHANGE TIMESTAMP;


ALTER TABLE my_test ALTER COLUMN sla_priority1_time DROP NOT NULL;
ALTER TABLE my_test ALTER COLUMN sla_priority2_time DROP NOT NULL;
ALTER TABLE my_test ALTER COLUMN sla_priority3_time DROP NOT NULL;


REORG TABLE my_test;

ALTER TABLE my_test ALTER COLUMN sla_priority4_time DROP NOT NULL;


REORG TABLE my_test;


INSERT INTO my_test (
       ...
       sla_priority1_time,
       sla_priority2_time,
       sla_priority3_time,
       sla_priority4_time,
       approvedDouAmount,
       year
)
SELECT ...
       sla_priority1_time,
       sla_priority2_time,
       sla_priority3_time,
       sla_priority4_time,
       NVL(pg.approvedDouAmount, 0),
       YEAR(NOW())
  FROM fin_attributes f, projgrp pg
WHERE f.projgrp_id = pg.id
   AND f.project_id IS NULL
   AND f.fin_projgrp_id IS NULL
UNION
SELECT ...
       sla_priority1_time,
       sla_priority2_time,
       sla_priority3_time,
       sla_priority4_time,
       NVL(p.approvedDouAmount, 0),
       YEAR(NOW())
  FROM fin_attributes f, project p
WHERE f.project_id = p.id
   AND f.projgrp_id IS NULL;


代码有四种颜色,绿色代表不需要执行REORG的语句,红色代表需要执行REORG的语句,蓝色是REORG语句。从代码上可以看出,红色高亮语句虽然要求使用REORG,但不及时运行REORG还可以让后续的几个语句继续执行。原因是DB2允许最多三条语句处于Reorg Pending状态,假如去除第一个REORG,语句“ALTER TABLE my_test ALTER COLUMN sla_priority4_time DROP NOT NULL;”就会执行失败。

结论:如果不确定那个是需要REORG哪个是不需要REORG,索性都用上REORG;虽然在允许有三条语句处于Reorg Pending状态,但最好每条ALTER TABLE对应一个REORG,因为处于Reorg Pending状态的表有可能会阻碍后续操作。

PS:REORG TABLE本身是DB2的command,不是正常的SQL语句(Statement)。如果在非命令行环境中想使用REORG的话,可以像下面那样调用存储过程间接执行REORG操作,执行前确保你所使用的帐号有调用这个存储过程的权限:

CALL SYSPROC.ADMIN_CMD('reorg table my_test')


最后来一段用Java动态执行SQL语句或DB2命令的代码。


//***************************************************************************  
// Licensed Materials - Property of IBM  
//  
// Governed under the terms of the International  
// License Agreement for Non-Warranted Sample Code.  
//  
// (C) COPYRIGHT International Business Machines Corp. 1997 - 2006  
// All Rights Reserved.  
//  
// US Government Users Restricted Rights - Use, duplication or  
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.  
//***************************************************************************  
//  
// SOURCE FILE NAME: TbOnlineInx.java  
//  
// SAMPLE: How to create and reorg indexes on a table  
//  
// SQL STATEMENTS USED:  
//         INCLUDE   
//         CREATE INDEX   
//         DROP INDEX  
//         REORG  
//         LOCK  
//  
// JAVA 2 CLASSES USED:  
//         Statement  
//         ResultSet  
//         File  
//         FileWriter  
//         Process  
//         BufferedReader  
//         InputStreamReader  
//  
// Classes used from Util.java are:  
//         Db  
//         JdbcException  
//  
// OUTPUT FILE: TbOnlineInx.out (available in the online documentation)  
// Output will vary depending on the JDBC driver connectivity used.  
//***************************************************************************  
//  
// For more information on the sample programs, see the README file.  
//  
// For information on developing Java applications see the Developing Java Applications book.  
//  
// For information on using SQL statements, see the SQL Reference.  
//  
// For the latest information on programming, compiling, and running DB2  
// applications, visit the DB2 Information Center at  
//     http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp  
//**************************************************************************/  
import java.sql.*;  
import java.lang.*;  
import java.io.*;  
public class TbOnlineInx  
{  
  public static void main(String argv[])   
  {  
    try  
    {  
      Db db = new Db(argv);  
      System.out.println();  
      System.out.println(  
        "THIS SAMPLE SHOWS HOW TO CREATE AND REORG ONLINE INDEXES/n" +  
        "ON TABLES.");  
              
      // connect to the 'sample' database  
      db.connect();  
        
      // create online index on a table   
      createIndex(db.con);  
        
      // reorg online index on a table   
      reorgIndex(db.con);  
        
      // drop online index created  
      dropIndex(db.con);  
        
      // disconnect from the 'sample' database  
      db.disconnect();  
    }  
    catch (Exception e)  
    {  
      JdbcException jdbcExc = new JdbcException(e);  
      jdbcExc.handle();  
    }  
  } // main  
  // How to create an index on a table with different levels  
  // of access to the table like read-write, read-only, no access   
  static void createIndex(Connection conn) throws Exception  
  {  
    
    System.out.print(  
      "/n-----------------------------------------------------------" +  
      "/nUSE THE SQL STATEMENT/n" +  
      "  CREATE INDEX/n" +  
      "TO CREATE AN INDEX/n");  
    // create an online index with read-write access to the table   
    System.out.print(  
      "/nTo create an index on a table allowing read-write access/n" +  
      "to the table, use the following SQL command:/n/n" +  
      "  CREATE INDEX index1 ON employee (lastname ASC)/n");  
      
    Statement stmt = conn.createStatement();  
    stmt.executeUpdate("CREATE INDEX index1 ON employee (lastname ASC)");  
    conn.commit();  
    
    dropIndex(conn);  
    
    // create an index on a table while allowing only read access to it   
    System.out.println(  
      "/nTo create an index on a table allowing only read access/n" +  
      "to the table, use the following two SQL commands:/n/n" +  
      "  LOCK TABLE employee IN SHARE MODE/n" +  
      "  CREATE INDEX index1 ON employee (lastname ASC)");  
    
    stmt.executeUpdate("LOCK TABLE employee IN SHARE MODE");  
    conn.commit();   
    stmt.executeUpdate("CREATE INDEX index1 ON employee (lastname ASC)");  
    conn.commit();  
    dropIndex(conn);  
     
    // create an online index allowing no access to the table  
    System.out.println(  
      "/nTo create an index on a table allowing no access to the /n" +  
      "table (only uncommitted readers allowed), use the /n" +  
      "following two SQL statements:/n/n" +  
      "  LOCK TABLE employee IN EXCLUSIVE MODE/n" +  
      "  CREATE INDEX index1 ON employee (lastname ASC)");  
      
    stmt.executeUpdate("LOCK TABLE employee IN EXCLUSIVE MODE");  
    conn.commit();  
    stmt.executeUpdate("CREATE INDEX index1 ON employee (lastname ASC)");   
    conn.commit();    
   
    stmt.close();  
  } // createIndex   
    
  // Create 3 CLP files for REORG command with write, read and no access,  
  // respectively.  
  static void createFiles(Connection conn) throws Exception   
  {  
    // get fully qualified name of the table  
    String tableName = "EMPLOYEE";   
    String schemaName = getSchemaName(conn, tableName);      
    String fullTableName = schemaName + "." + tableName;        
         
    // reorg command has to be executed with three different options, namely,  
    // 'with write access', 'with read access' and 'with no access'  
    String[] fileNames = { "ReorgCmdAllowWrite.db2",   
                           "ReorgCmdAllowRead.db2",   
                           "ReorgCmdAllowNone.db2" };  
       
    String[] options = { " WRITE ACCESS",  
                         " READ ACCESS",  
                         " NO ACCESS" };  
    for (int i = 0; i < 3; i++)  
    {   
      // create a CLP file with the REORG command and execute the file  
      File outputFile = new File(fileNames[i]);  
      FileWriter out = new FileWriter(outputFile);  
      
      out.write("CONNECT TO SAMPLE;/n");  
      out.write("REORG INDEXES ALL FOR TABLE " + fullTableName +   
                " ALLOW" + options[i] + ";/n");  
      out.write("CONNECT RESET;");  
      out.close();     
          
      // on exit, delete the temporary files created   
      outputFile.deleteOnExit();                  
    }  
  } //createFiles    
   
  // How to reorg an index on a table with different levels of   
  // access to the table like read-write, read-only, no access   
  static void reorgIndex(Connection conn)   
  {  
    System.out.print(  
      "/n-----------------------------------------------------------/n" +  
      "/nUSE THE SQL STATEMENT:/n"+  
      "  REORG/n" +  
      "TO REORGANIZE A TABLE./n");  
      
    String[] fileNames = { "ReorgCmdAllowWrite.db2",   
                           "ReorgCmdAllowRead.db2",   
                           "ReorgCmdAllowNone.db2" };  
      
    String[] options = { " write access",  
                         " read access",  
                         " no access" };  
    try  
    {     
      // create 3 files with REORG commands  
      createFiles(conn);  
        
      for (int i = 0; i < 3; i++)  
      {   
        System.out.println(  
          "/nReorganize the indexes on a table allowing" + options[i] +   
          "/n-----------------------------------------------------------");  
                   
        String s = null;    
        String execCmd = "db2 -tvf " + fileNames[i];  
                
        // execute the command to run the CLP file  
        Process p = Runtime.getRuntime().exec(execCmd);             
                                              
        // open streams for the process's input and error    
        BufferedReader stdInput = new BufferedReader(new   
                                        InputStreamReader(p.getInputStream()));  
        BufferedReader stdError = new BufferedReader(new  
                                        InputStreamReader(p.getErrorStream()));  
      
        // read the output from the command and set the output variable with   
        // the value  
        while ((s = stdInput.readLine()) != null)  
        {  
          System.out.println(s);  
        }  
        
        // read any errors from the attempted command and set the error    
        // variable with the value  
        while ((s = stdError.readLine()) != null)   
        {  
          System.out.println(s);  
        }  
       
        p.destroy();  
                
      } // for              
    } // try  
      
    catch (IOException e)  
    {  
      e.printStackTrace();  
      System.exit(-1);               
    }    
       
    catch (Exception e)  
    {  
      JdbcException jdbcExc = new JdbcException(e);  
      jdbcExc.handle();  
    }         
           
  } // reorgIndex  
    
  // How to drop the index on a table   
  static void dropIndex(Connection conn)  
  {  
    System.out.println(  
      "/nUSE THE SQL STATEMENT/n" +  
      "  DROP/n" +  
      "TO DROP AN INDEX:");  
    try  
    {  
      // drop the indexes   
      System.out.println(  
        "  Execute the statement/n" +  
        "    DROP INDEX index1/n" +  
        "/n-----------------------------------------------------------");  
      Statement stmt = conn.createStatement();  
      stmt.executeUpdate("DROP INDEX index1");  
      conn.commit();  
      stmt.close();  
    }  
    catch (Exception e)  
    {  
      JdbcException jdbcExc = new JdbcException(e);  
      jdbcExc.handle();  
    }  
  } // dropIndex   
  // function to get the schema name for a particular table  
  static String getSchemaName(Connection conn, String tableName) throws Exception  
  {  
    Statement stmt = conn.createStatement();  
    ResultSet rs = stmt.executeQuery(  
                     "SELECT tabschema "+  
                     "  FROM syscat.tables "+  
                     "  WHERE tabname = '"+ tableName + "'");  
                       
    boolean result = rs.next();  
    String schemaName = rs.getString("tabschema");  
    rs.close();  
    stmt.close();  
      
    // remove the trailing white space characters from schemaName before   
    // returning it to the calling function  
    return schemaName.trim();  
  } // getSchemaName    
} // TbOnlineInx   




下面是ibm相关网站的一篇文章:
http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/c0023297.htm

Using the ALTER TABLE statement to alter columns of a table


Before creating your database, you need to consider the type and organization of the data that you want to store in it. You need to plan what kind of data your business might need to use and how your business will use that data. However, things change. Despite good planning, there might be new requirements that necessitate changes to the tables in the database. You can use the ALTER TABLE statement to alter the row format of table data: dropping columns, changing the types of columns, and certain other column attributes.

Restrictions on table access after ALTER TABLE statements containing REORG-recommended operations


It is important that you plan the implementation of the table alterations well. Perhaps the most important thing to realize when running an ALTER TABLE statement containing a REORG-recommended operation is that once the ALTER TABLE statement has executed, the table will be placed in the Reorg Pending state. This means that the table is inaccessible for almost all operations until you perform a REORG. See the ALTER TABLE statement in the SQL Reference for the complete list of ALTER TABLE operations, some of which are also called REORG-recommended operations.
After an ALTER TABLE statement containing REORG-recommended operations, you can execute only the following statements on a table:

  
   REORG TABLE
   DROP TABLE
   ALTER TABLE
   RENAME TABLE

To allow data recovery in case of a REORG failure, table data might be read using scan-based read only statements, that is, using TABLE SCAN statements. In addition, index-based table access is not allowed. If a table scan-based access is used instead of index-based access, you can also issue a SELECT statement from the table.
The following ALTER TABLE statements require row data validation, and are not allowed following a REORG-recommended ALTER. However, you can execute most of the other ALTER TABLE statements. The ALTER TABLE statements that you cannot use are those that require scanning of column data to verify the validity of the alteration operations. Specifically, this means that you cannot execute the following statements on a table:

      ADD UNIQUE CONSTRAINT
      ADD CHECK CONSTRAINT
      ADD REFERENTIAL CONSTRAINT
      ALTER COLUMN SET NOT NULL
      ALTER TABLE ADD REFERENTIAL CONSTRAINT
      ALTER TABLE ADD CONSTRAINT
      ALTER TABLE ADD UNIQUE CONSTRAINT

Examples of ALTER TABLE statements containing REORG-recommended operations
In addition to placing restrictions on table access after an ALTER TABLE statement containing REORG-recommended operations, the DB2® database manager allows you to specify only three REORG-recommended operations before you perform a classic REORG and before additional REORG-recommended operations will succeed. For this reason, you should code each ALTER TABLE statement containing REORG-recommended operations to change the attributes of as many columns as possible. For example, if you specify the following sequence of ALTER TABLE statements containing only one REORG-recommended operation in each, you will be unable to specify any subsequent ALTER TABLE statements that would require a new row format until you perform a classic REORG:

   ALTER TABLE foo DROP COLUMN C1
   ALTER TABLE foo DROP COLUMN C2
   ALTER TABLE foo DROP COLUMN C3

You could, however, replace the three ALTER TABLE statements with a single one:

   ALTER TABLE foo DROP COLUMN C1 DROP COLUMN C2 DROP COLUMN C3

Since you can alter only one attribute per column in a single SQL statement--for example, type or nullability—it is possible that changing a column to a new format could require the use of more than one ALTER TABLE statement containing REORG-recommended operations. In such a case, it is important that the order of alterations not allow one alteration to preclude another due to the Reorg Pending state. This means that you should perform operations requiring table data access using the first ALTER TABLE statement containing REORG-recommended operations. For example, if column C1 is an integer and is NULLABLE and you want to change this column to be a NOT NULLABLE BIGINT, the following sequence will fail:

   ALTER TABLE bar ALTER COLUMN C1 SET DATA TYPE BIGINT
   ALTER TABLE bar ALTER COLUMN C1 SET NOT NULL

The reason for the failure is that the second ALTER TABLE statement requires a scan of the column C1 to see whether any rows contain the value NULL. Since the table is placed in Reorg Pending state after the first statement, the scan for the second statement cannot be performed.
However, the following sequence will succeed because the first statement does not access the data and does not put the table in Reorg Pending state:


   ALTER TABLE bar ALTER COLUMN C1 SET NOT NULL
   ALTER TABLE bar ALTER COLUMN C1 SET DATA TYPE BIGINT

You can perform many operations that alter a table that do not constitute REORG-recommended operations regardless of the number of REORG-recommended operations that you have specified. These include:

   ADD COLUMN
   ALTER COLUMN DEFAULT VALUE
   RENAME TABLE
   ALTER COLUMN SET DATA TYPE VARCHAR/VARGRAPHIC/CLOB/BLOB/DBCLOB

Concurrency during ALTER TABLE execution

Any ALTER TABLE statement requires exclusive access to a table, as it modifies in-memory structures. For certain statement options in particular, ALTER TYPE and DROP COLUMN—rows in table catalogs will be locked exclusively for UPDATE or DELETE. For this reason, once the ALTER TABLE statement completes, it is important that the unit of work containing the statement be committed or rolled back as soon as possible.

ALTER TABLE authority considerations

After using an ALTER TABLE statement containing REORG-recommended operations, you must use the classic REORG TABLE statement to make the table accessible again. Having ALTER authority on the table does not necessarily mean that you have the authority to use the REORG TABLE statement; you must have REORG authority.

CASCADE versus RESTRICT semantics when dropping columns

When dropping a column, DB2 must ensure that any database objects that are dependent on that column—for example, views, triggers, and indexes—are also updated. Two options are available when you specify an ALTER TABLE DROP COLUMN statement: CASCADE and RESTRICT. These options affect how dependent database objects are updated.

CASCADE
    CASCADE, the default, automatically handles the dropping of database objects that are dependent on the column being dropped. You should use CASCADE only when you feel confident that you understand the full impact of such an operation. If you do not understand the database object dependencies well, using the CASCADE option might result in performance degradation as a result of implicitly dropping an index. Other side effects could include DML failures on views that were marked inoperative or data integrity issues stemming from inoperative triggers. The following objects are implicitly dropped when you use CASCADE:

        Identity attributes
        SQL routines
        Indexes
        Unique constraints
        Triggers
        Foreign key constraints
        Primary key constraints (this will also cause the implicit deletion of any dependent foreign key constraints)
        Check constraints
        Generated column data
        Views
        Packages

RESTRICT
    RESTRICT causes the ALTER TABLE statement to fail if any database object other than a package is found to have a dependency on the column being dropped. Often, it is difficult to generate the complete list of dependent objects for a particular column, but it might be desirable to evaluate each object to decide whether a replacement index should be created following a DROP COLUMN operation. In cases such as this, you might want to specify the RESTRICT option and remove or plan for the re-creation of each affected object. The object type and name first detected with a column-level dependency are returned as part of the error message if the ALTER TABLE statement fails.




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics