临时表不会从DB中删除

时间:2013-11-13 18:27:38

标签: sql-server-2008 tsql

我有一个大型查询,首先选择#tmp1。在选择语句之前,我有以下内容:

USE Sandbox

--if the table exists, we want to delete it first
IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = '#tmp1'))
BEGIN
    drop table dbo.#tmp1
END

问题是当我运行整个查询时出现错误:

Msg 2714, Level 16, State 6, Line 51
There is already an object named '#tmp1' in the database.

如果我突出显示上述声明并运行它,我得到:

Command(s) completed successfully.

但如果我再次运行查询,我会得到上面的错误。

我也试过这两个(结果“成功完成”,在尝试运行查询时仍然出现上述错误:

if exists (select * from sys.objects where name = '#tmp1' and type = 'u')
    drop table dbo.#tmp1

IF OBJECT_ID('dbo.#tmp1', 'U') IS NOT NULL
  DROP TABLE dbo.#tmp1

任何人都可以看到我可能做错了吗?

我总共使用了4个临时表,我的大型SQL语句的结构如下:

USE Sandbox

If #tmp1 exists, drop it    
If #tmp2 exists, drop it    
If #tmp3 exists, drop it   
If #tmp4 exists, drop it

Declare variables

select into #tmp1    
select into #tmp2    
select into #tmp3    
select into #tmp4    
select from #tmp1    
select from #tmp2    
select from #tmp3    
select from #tmp4

1 个答案:

答案 0 :(得分:5)

临时表位于tempdb ...但您当前的代码正在检查Sandbox数据库中是否存在该对象。

更改您的代码以使用由3个部分组成的名称,包括临时表所在的数据库tempdb

IF OBJECT_ID('tempdb.dbo.#tmp1', 'U') IS NOT NULL
  DROP TABLE dbo.#tmp1