PRB: CREATE TABLE Appears to Ignore IF Statements

ID: Q120875


The information in this article applies to:
  • Microsoft SQL Server for OS/2, version 4.2
  • Microsoft SQL Server version 4.2x


SYMPTOMS

If a CREATE TABLE statement is placed inside an IF block to prevent re- creating a table that already exists, the duplicate table name error will still be raised.


WORKAROUND

When a query is submitted, object existence and resolution is done at parse time, not execution time. This will cause the CREATE TABLE statement to fail the query with the 2714 error.

The following code works properly:


   IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME="TEST")
     DROP TABLE TEST
   GO

   CREATE TABLE TEST (C1 int)
   GO 

The following code does not work properly:

   IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME="TEST")
  CREATE TABLE TEST (C1 int)
   GO 

Since there are times when you do not want to drop the table, the following procedure can be used:

Run the following script once on each server where the table needs to used, preferably when nobody else is accessing the table. The script will create a stored procedure that will build the table. It is necessary to rename the table so that the stored procedure TAB_CREATE will compile without error when created.

   IF EXISTS(SELECT * FROM SYSOBJECTS WHERE id=OBJECT_ID("TEST"))
        EXEC SP_RENAME TEST,TEST1
   GO
   CREATE PROC TAB_CREATE
        AS CREATE TABLE TEST (C1 int)
   IF EXISTS(SELECT * FROM SYSOBJECTS WHERE id=OBJECT_ID("TEST1"))
        EXEC SP_RENAME TEST1,TEST 

Once the above script has been run, the following code can be used in scripts to resolve the duplicate table name error:

   IF EXISTS(SELECT * FROM SYSOBJECTS WHERE id=OBJECT_ID("TEST"))
        PRINT 'The table already exists...'
   ELSE
   BEGIN
        PRINT 'Create the table...'
        EXEC TAB_CREATE
   END 

Additional query words: Transact-SQL Windows NT

Keywords : kbprg SSrvServer SSrvWinNT
Version : 4.2 | 4.2
Platform : OS/2 WINDOWS
Issue type :


Last Reviewed: March 20, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.