【问题标题】:drop temp table but already founded 'There is already an object named '#temp' in the database'删除临时表但已经建立'数据库中已经有一个名为'#temp'的对象'
【发布时间】:2019-09-18 13:04:04
【问题描述】:

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

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-2012 temp-tables


【解决方案1】:

稍微改变一下你的逻辑流程。如果重要的是当INSERT 发生时#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 * 是生产代码中等待发生的事故。

【讨论】:

  • 谢谢,但我需要知道为什么我不能@EricBrandt
  • 来自the documentation:DROP TABLE and CREATE TABLE should not be executed on the same table in the same batch. Otherwise an unexpected error may occur. 如上面评论中链接的问题所述。 INTO 子句在与DROP 相同的批处理中在后台生成CREATE TABLE,并且您会收到提示的错误。
猜你喜欢
  • 2011-03-29
  • 2021-09-24
  • 2019-05-12
  • 2016-04-08
  • 2014-08-01
  • 2010-11-12
  • 2021-05-10
  • 2013-10-21
  • 1970-01-01
相关资源
最近更新 更多