如果存在,则删除临时表。

8

朋友们,

我正在创建一个临时表。由于脚本可能会运行多次,因此我需要检查临时表是否存在,如果存在则删除它。我编写了下面的代码,但是当我运行脚本两次时,会出现错误,指出表已经存在:

数据库中已经存在名为 '#lu_sensor_name_19' 的对象

看起来当表不为空时,IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL并没有返回true。我做错了什么?

IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL 
BEGIN 
    DROP TABLE #lu_sensor_name_19 
END

CREATE TABLE #lu_sensor_name_19(
    sensorname_id int NOT NULL,
    sensorname nvarchar(50) NOT NULL,
    paneltype_id smallint NOT NULL,
    panel_version_id int NULL,
    prefix_allowed tinyint NOT NULL,
    base_allowed tinyint NOT NULL,
    suffix_allowed tinyint NOT NULL,
    key_value int NULL,
    sort_index int NULL,
    device_allowed tinyint NOT NULL,
    sensor_name_group_id smallint NOT NULL,
    )

可能是删除当前spid的临时表的重复问题。 - bummi
2个回答

22

临时表会在 tempdb 中创建。请尝试以下方法:

IF OBJECT_ID('tempdb..#lu_sensor_name_19') IS NOT NULL 
BEGIN 
    DROP TABLE #lu_sensor_name_19 
END

CREATE TABLE #lu_sensor_name_19...

SQL Server 2016增加了一行代码实现删除功能的能力:

DROP TABLE IF EXISTS #lu_sensor_name_19 

CREATE TABLE #lu_sensor_name_19...

3

使用此功能。

IF OBJECT_ID('tempdb.dbo.##myTempTable', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##myTempTable;
    --DROP TABLE ##tempdb.dbo.myTempTable;
    /* Above line commented out, because it generates warning:
    "Database name 'tempdb' ignored, referencing object in tempdb.",
    which is a pain in the neck if you are using a temp table to generate SQL code,
    and want to print the code to the screen.*/
END;
GO

CREATE TABLE ##myTempTable(
    FooBar nvarchar(128) not null,
);

而在 SQL Server 2016 中,您可以编写:

DROP TABLE IF EXISTS ##myTempTable

在SQL Server 2017中,"##"对我无效。我需要写成"tempdb..#"。 - MarJer
@MarJer ## 是一个全局临时表。# 是一个会话范围的临时表。如果你使用 # 创建了一个表,就不能使用 ##,反之亦然。此外,“..”约定与执行用户的默认模式紧密耦合。使用实际模式代替“..”。使用“..”是不规范的。在存储过程中也永远不要使用它,因为它会导致引擎必须暂时锁定系统字典来查找当前用户的默认模式。始终要明确。 - John Zabroski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接