0

I tried the following code in SQL Server and met a strange error:

IF OBJECT_ID(N'tempdb..#t1') IS NULL
BEGIN
CREATE TABLE #t1(
    F1 DATE NOT NULL
)
END

IF OBJECT_ID(N'tempdb..#t1') IS NULL
BEGIN
CREATE TABLE #t1(
    F1 DATE NOT NULL
)
END

Error:

'#t1' existed.

I have no idea why this error occurs?

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
xiagao1982
  • 1,077
  • 1
  • 13
  • 25
  • It seems like your IF clauses are being evaluated before your first create table is executed, if you put a GO statement after your first IF...END then you don't receive the error. – Steve Ford Dec 11 '12 at 09:52

6 Answers6

2

This is idea

IF OBJECT_ID(N'tempdb..#t1') IS NULL
BEGIN
   CREATE TABLE #t1( F1 DATE NOT NULL )
END
GO

IF OBJECT_ID(N'tempdb..#t1') IS NULL
BEGIN
   CREATE TABLE #t1( F1 DATE NOT NULL )
END
GO
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
1

Try this instead:

IF NOT exists(SELECT 1
              FROM information_schema.columns 
              WHERE table_name LIKE '#t1%')
BEGIN
CREATE TABLE #t1(
    F1 DATE NOT NULL
)
END
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
1

Try this one :

IF Not EXISTS (select * from sys.objects where Name = 'tempdb..#t1')

BEGIN
CREATE TABLE #t1(
    F1 DATE NOT NULL
)
END
Maryam Arshi
  • 1,974
  • 1
  • 19
  • 33
1

This is not runtime Error, it's a "compiletime" error

--Drop table #t1  // call this alone to ensure that it's not existing, then call the rest, nothing will be printed

Print 0

IF OBJECT_ID('tempdb..#t1') IS NULL
BEGIN
Print 1
CREATE TABLE #t1(
    F1 DATE NOT NULL
)
END



IF OBJECT_ID('tempdb..#t1') IS NULL
BEGIN
Print 2
CREATE TABLE #t1(
    F1 DATE NOT NULL
)
END
bummi
  • 27,123
  • 14
  • 62
  • 101
1
  • SQL Server does not store temp table with given name ('#t1'). Instead it adds a suffix to make it 128 character long. Therefore you won't find '#t1'.

You can use LIKE '#t1%' to find it.

IF NOT EXISTS (select * from tempdb.sys.tables where name like '#t1%')
  • Also you should add GO after your first query to mark the end of batch.

Use it as below;

--DROP TABLE #t1
--GO

    IF OBJECT_ID(N'tempdb..#t1') IS NULL
    BEGIN
    CREATE TABLE #t1(
        F1 DATE NOT NULL
    )
    END
    GO

    IF NOT EXISTS(select * from tempdb.sys.tables where name like '#t1%')
    BEGIN
    CREATE TABLE #t1(
        F1 DATE NOT NULL
    )
    END
Kaf
  • 33,101
  • 7
  • 58
  • 78
1

Your code is actually fine, but there's a limitation in SQL Server which means that during the query optimization phase it will fail. Please see the answers here - why does sql server think a temp table already exists when it doesnt.

Community
  • 1
  • 1
Matt Whitfield
  • 6,436
  • 3
  • 29
  • 44