0

I have a problem while drop temp table. If run below query in 1 time its show error

There is already an object named '#a' in the database.

Please run query in 1 time

if(OBJECT_ID('tempdb..#a','U')Is not null)
Begin
drop table #a
End

Create table #a
(
id int
)

insert into #a
select 1

select * from #a


if(OBJECT_ID('tempdb..#a','U')Is not null)
Begin
drop table #A
End

Create table #a
(
id int
,name varchar(10)
)

insert into #a
select 2,'name'

select * from #A
Sam
  • 61
  • 1
  • 6

2 Answers2

1

TRY THIS: you have to use GO to make a batch and execute each separately because you are creating same temporary table again and it's executing it at once:

if(OBJECT_ID('tempdb..#a','U')Is not null)
Begin
    drop table #a
End
GO
Create table #a (id int)

insert into #a
select 1

select * from #a

if(OBJECT_ID('tempdb..#a','U')Is not null)
Begin
    drop table #a
End
GO
Create table #a(id int,name varchar(10))
insert into #a
select 2,'name'

select * from #a

NOTE: Please try to use the similar CASE for the table name

Shushil Bohara
  • 5,556
  • 2
  • 15
  • 32
0

You miss 'GO' statement.

Without 'GO' in between, the whole thing will be considered as one single script and when the select statement looks for the column, it won't be found.

With 'GO', it will consider the part of the script up to 'GO' as one single batch and will execute before getting into the query after 'GO'.

if(OBJECT_ID('tempdb..#a','U')Is not null)
Begin
drop table #a
End
go
Create table #a
(
 id int
 )

insert into #a
select 1

select * from #a


if(OBJECT_ID('tempdb..#a','U')Is not null)
Begin
drop table #a
End

go

Create table #a
(
 id int
 ,name varchar(10)
)

insert into #a
select 2,'name'

select * from #a

Please mark it as answer if it's useful.

SynozeN Technologies
  • 1,337
  • 1
  • 14
  • 19