PRB: CREATE TABLE Appears to Ignore IF StatementsID: Q120875
|
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.
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
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME="TEST")
CREATE TABLE TEST (C1 int)
GO
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
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