首页 > 解决方案 > SQL Server 临时表重新创建

问题描述

select * 
into #t1 
from testcur;

if object_id('tempdb..#t1') is not null
    drop table #t1;

select * 
into #t1 
from testcur;

有没有办法再次使用创建临时表?在这种情况下#t1

标签: sqlsql-server

解决方案


如果你打算在 SSMS (SQL Server Management Studio) 中使用这个脚本,你会得到一个实际上是编译错误的错误:

消息 2714,级别 16,状态 1,第 12 行
数据库中已经有一个名为“#t1”的对象。

SSMS 不明白您已删除表并要再次创建,因此尽管您的查询有效,但它仍会显示错误。

要使 SSMS 对您的脚本感到满意,请在第二次尝试创建表之前使用 GO

select * 
into #t1 
from testcur;

if object_id('tempdb..#t1') is not null
    drop table #t1;

GO -- use GO

select * 
into #t1 
from testcur;

推荐阅读