删除临时表(如果存在) [英] Drop temp table if it exists

查看:40
本文介绍了删除临时表(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,

我正在创建一个临时表.该脚本可能会运行多次,因此我需要检查临时表是否存在,然后将其删除.我写了下面的代码,但是在运行脚本两次时出现错误,表已经存在:

I am creating a temp table. The script may be run several times so I need to check if the temp table exist then drop it. I have the written the code below but I get an error when running the script twice, that the table already exists:

数据库中已经有一个名为#lu_sensor_name_19"的对象.

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

It appears that IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL does not return true when the tablle is not null. What am I doing wrong?

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,
    )

推荐答案

Temp #Tables 在 tempdb 中创建.试试这个:

Temp #Tables are created in tempdb. Try this:

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 添加了一行删除的功能:

SQL Server 2016 added the ability to do the drop in one line:

DROP TABLE IF EXISTS #lu_sensor_name_19 

CREATE TABLE #lu_sensor_name_19...

这篇关于删除临时表(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆