为什么我不能在T-SQL中重用临时表?

Mat*_*ttB 4 sql sql-server temp-tables

这是一些示例代码:

if object_id('tempdb..#TempList') is not null drop table #TempList

create table #TempList (
   ID int,
   Name varchar(20)
)

insert into #TempList values (1, 'Alpha')
insert into #TempList values (2, 'Beta')
insert into #TempList values (3, 'Gamma')
insert into #TempList values (4, 'Delta')
insert into #TempList values (5, 'Omega')

select * from #TempList

if object_id('tempdb..#TempList') is not null drop table #TempList
drop table #TempList

create table #TempList (
   ID_New int,
   AnotherID int,
   Name_New varchar(40)
)

insert into #TempList values (100, 110, 'Orange')
insert into #TempList values (101, 111, 'Red')
insert into #TempList values (102, 112, 'Purple')
insert into #TempList values (103, 113, 'Blue')
insert into #TempList values (104, 114, 'Green')

select * from #TempList
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误:

Msg 2714, Level 16, State 1, Line 19
There is already an object named '#TempList' in the database.
Run Code Online (Sandbox Code Playgroud)

我无法在同一个SQL脚本中重复使用相同的临时表名称吗?有没有办法重复使用相同的临时表名称?

谢谢.

Gen*_*нин 6

更改

if object_id('tempdb..#TempList') is not null drop table #TempList
drop table #TempList

create table #TempList (
Run Code Online (Sandbox Code Playgroud)

if object_id('tempdb..#TempList') is not null drop table #TempList
drop table #TempList

GO;

create table #TempList (
Run Code Online (Sandbox Code Playgroud)

SQL Server查询优化器变得混乱.

它看到你第二次创建同一个表.
请注意,表drop(以及create)具有概率结果,
结果只能在运行时知道(不是在语法控制或查询exec计划创建,也就是SQL Server术语中的"编译")


DFo*_*k42 5

对我来说似乎是一个解析器错误.我打赌它看到两个create table语句创建相同的表并抛出错误,无论drop语句如何.用go语句打破它可以正常工作.

create table #Temp (ID int)
insert into #Temp (ID)
select 1 union all select 2

select ID from #Temp

drop table #Temp
go
create table #Temp (ID int)

insert into #Temp (ID)
select 10 union all select 11

select ID from #Temp

drop table #Temp
Run Code Online (Sandbox Code Playgroud)