3

我有一个大查询,从选择#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
4

1 回答 1

6

Temp tables live in tempdb... but your current code is checking for the object to exist in your Sandbox database.

Change your code to use a 3-part name, including the database, tempdb, where the temporary table lives:

IF OBJECT_ID('tempdb.dbo.#tmp1', 'U') IS NOT NULL
  DROP TABLE dbo.#tmp1
于 2013-11-13T18:35:15.867 回答