Errors and warnings generated by alter table modify  Renaming tables and other objects

Chapter 8: Creating Databases and Tables

Scripts generated by if exists()...alter table

Scripts that include constructs like the following may produce errors if the table described in the script does not include the specified column:

if exists (select 1 from syscolumns
    where id = object_id("some_table")
        and name = "some_column")
    begin
        alter table some_table drop some_column
    end

In this example, some_column must exist in some_table for the batch to succeed.

If some_column exists in some_table, the first time you run the batch, alter table drops the column. On subsequent executions, the batch does not compile.

Adaptive Server raises these errors while preprocessing this batch, which are similar to those that are raised when a normal select tries to access a nonexistent column. These errors are raised when you modify a table’s schema using clauses that require a data copy. If you add a null column, and use the above construct, Adaptive Server does not raise these errors.

To avoid such errors when you modify a table’s schema, include alter table in an execute immediate command:

if exists (select 1 from syscolumns
       where id = object_id("some_table")
         and name = "some_column")
begin
    exec ("alter table some_table drop
        some_column")
end

Because the execute immediate statement is run only if the if exists() function succeeds, Adaptive Server does not raise any errors when it compiles this script.

You must also use the execute immediate construct for other uses of alter table, for example, to change the locking scheme, and for any other cases when the command does not require data copy.





Copyright © 2005. Sybase Inc. All rights reserved. Renaming tables and other objects

View this book as PDF