友
我正在创建临时表。脚本可能会运行几次,所以我需要检查临时表是否存在然后删除它。我编写了下面的代码但是在运行脚本两次时出现错误,表已经存在:
数据库中已有一个名为“#lu_sensor_name_19”的对象。
当tablle不为null时,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,
)
答案 0 :(得分:7)
Temp #Tables在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...
答案 1 :(得分:1)
使用此功能。
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