Sql server 2012 删除临时表,但已建立“数据库中已存在名为“temp”的对象”

Sql server 2012 删除临时表,但已建立“数据库中已存在名为“temp”的对象”,sql-server-2012,temp-tables,Sql Server 2012,Temp Tables,在部分代码中,当我删除一个临时表并重用它时,需要在两个临时表之间进行交换,但我不能 create table #temp (id int) create table #swap (id int) drop table #temp select * into #temp from #swap drop table #swap drop table #temp 我收到这个错误 Msg 2714,16级,状态1,第6行 数据库中已存在名为“temp”的对象 只要稍微改变一下你的逻辑流程。如果重

在部分代码中,当我删除一个临时表并重用它时,需要在两个临时表之间进行交换,但我不能

create table #temp (id int)
create table #swap (id int)

drop table #temp

select * into #temp from #swap

drop table #swap
drop table #temp
我收到这个错误

Msg 2714,16级,状态1,第6行 数据库中已存在名为“temp”的对象


只要稍微改变一下你的逻辑流程。如果重要的是插入时temp为空,那么这应该满足您的需要

create table #temp (id int)
create table #swap (id int)

<Add loop logic here>

truncate table #temp

insert #temp(id)
select id from #swap

<Close out loop logic>

drop table #swap
drop table #temp

我还明确了列名。SELECT*是生产代码中等待发生的意外事件。

您需要在第二个创建表和第一个删除表之后添加GO。我不能使用GO,因为此代码是其中的一部分。谢谢您,但我需要知道为什么我不能执行@EricBrandtFrom:DROP TABLE和CREATE TABLE不应在同一批中的同一个表上执行。否则,可能会发生意外错误。正如上面一条评论中的问题所指出的那样。INTO子句在与DROP相同的批处理中在后台生成一个CREATETABLE,您将得到注意到的错误。