Sql 删除临时表(如果存在)
朋友们 我正在创建一个临时表。脚本可能会运行多次,因此我需要检查临时表是否存在,然后将其删除。我已经编写了下面的代码,但在两次运行脚本时出现错误,即表已经存在: 数据库中已经有一个名为“#lu_sensor_name_19”的对象 如果对象ID('alarm..lu#sensor_name_19')不为空,则Sql 删除临时表(如果存在),sql,sql-server,Sql,Sql Server,朋友们 我正在创建一个临时表。脚本可能会运行多次,因此我需要检查临时表是否存在,然后将其删除。我已经编写了下面的代码,但在两次运行脚本时出现错误,即表已经存在: 数据库中已经有一个名为“#lu_sensor_name_19”的对象 如果对象ID('alarm..lu#sensor_name_19')不为空,则似乎在表格不为空时不返回true。我做错了什么 IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL BEGIN DROP
似乎在表格不为空时不返回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,
)
Temp#表是在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...
用这个
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##是一个全局临时表是一个会话范围的临时表。如果使用#创建表,则不能使用#,反之亦然。此外,“…”约定与执行用户的默认模式紧密耦合。改用实际的模式。“.”是草率的。您也不应该在存储过程中使用它,因为它将导致引擎必须临时锁定系统字典以查找当前用户的默认模式。永远要明确。