确定SQL Server中是否存在临时表的最佳方法是什么?

时间:2021-04-24 07:38:13

When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).

在编写我计划重新运行的T-SQL脚本时,我经常使用临时表来存储临时数据。由于临时表是动态创建的,我希望能够删除该表,只有它存在(在我创建它之前)。

I'll post the method that I use, but I'd like to see if there is a better way.

我将发布我使用的方法,但我想看看是否有更好的方法。

3 个解决方案

#1


25  

IF Object_Id('TempDB..#TempTable') IS NOT NULL
BEGIN
    DROP TABLE #TempTable
END

#2


14  

The OBJECT_ID function returns the internal object id for the given object name and type. 'tempdb..#t1' refers to the table #t1 in the tempdb database. 'U' is for user-defined table.

OBJECT_ID函数返回给定对象名称和类型的内部对象ID。 'tempdb ..#t1'是指tempdb数据库中的表#t1。 'U'用于用户定义的表。

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

CREATE TABLE #t1
(
  id INT IDENTITY(1,1),
  msg VARCHAR(255)
)

#3


0  

SELECT name
FROM sysobjects
WHERE type = 'U' AND name = 'TempTable'

#1


25  

IF Object_Id('TempDB..#TempTable') IS NOT NULL
BEGIN
    DROP TABLE #TempTable
END

#2


14  

The OBJECT_ID function returns the internal object id for the given object name and type. 'tempdb..#t1' refers to the table #t1 in the tempdb database. 'U' is for user-defined table.

OBJECT_ID函数返回给定对象名称和类型的内部对象ID。 'tempdb ..#t1'是指tempdb数据库中的表#t1。 'U'用于用户定义的表。

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

CREATE TABLE #t1
(
  id INT IDENTITY(1,1),
  msg VARCHAR(255)
)

#3


0  

SELECT name
FROM sysobjects
WHERE type = 'U' AND name = 'TempTable'