Create table but Drop it if the table exists already

后端 未结 2 1368
名媛妹妹
名媛妹妹 2021-01-05 18:58

I am working on a request where I have to create a table to insert some data. So, obviously I will have first have a delete table st. before the create st. but when I am run

2条回答
  •  被撕碎了的回忆
    2021-01-05 19:25

    You can create a stored procedure owned by SYSDBA or other admin level user with adequate DROP TABLE and CREATE TABLE privileges that does the following:

    1. Check DBC.Tables to see if object exists.
    2. If object exists, drop it.
    3. Run the DDL to recreate the table: CREATE TABLE . AS . WITH DATA AND STATS;

    You can make it more dynamic by accepting additional parameters on whether the data and/or stats should be copied to the new table.

    If you are using BTEQ, you can do something similar (BTEQ command syntax may be a little off but close enough to get the point across):

    SELECT 1 
    FROM DBC.TABLES 
    WHERE DatabaseName = ''
      AND TableName = ''
      AND TableKind = 'T' /* Make sure it is in fact a table, not a view, macro etc */
    
    
    .IF ACIVITYCOUNT = 0 THEN GOTO CreateNewTable;
    
    DROP TABLE .;
    
    .IF ERRORCODE = 3807 THEN GOTO CreateNewTable; /* Table dropped by another process? */
    .IF ERRORCODE > 0 THEN .QUIT ERRORCODE; /* Unexpected error */
    
    .LABEL CreateNewTable;
    
    CREATE . AS . WITH DATA AND STATISTICS;
    

提交回复
热议问题