首页 > 解决方案 > 删除临时表但已经建立'数据库中已经有一个名为'#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

我收到此错误

消息 2714,级别 16,状态 1,第 6 行 数据库中已经有一个名为“#temp”的对象。

标签: sql-server-2012temp-tables

解决方案


稍微改变一下你的逻辑流程。如果重要的是发生#temp时它是空的INSERT,那么这应该可以满足您的需要。

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 *是在生产代码中等待发生的事故。


推荐阅读