数据库中已经有一个名为“#xxxx”的对象

There is already an object named '#xxxx' in the database

我在一个脚本中dropping/creating多次table临时

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims

select * into #uDims from table1

.... do something else 

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims

select * into #uDims from table2 -- >> I get error here

.... do something else 

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims

select * into #uDims from table3  -- >> and here

.... do something else 

尝试 运行 脚本时,我得到

There is already an object named '#uDims' in the database.

第二个和第三个"select into..."

这显然是一个编译时错误。如果我 运行 逐节编写脚本,一切都会正常进行。

这个问题有很多解决方法,但我想知道为什么 SSMS 对此不满意。

Ivan Starostin 是正确的。我在 SQL 上测试了这个 TSQL,它工作正常。

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims
select top 10 *  into #uDims from tblS
go 
IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims
select top 10 * into #uDims from Waters

没有走,我得到了和你一样的错误(闪烁)。

您不能在存储过程中多次创建相同的临时文件 table。

根据 documentation(在备注部分),

If more than one temporary table is created inside a single stored procedure or batch, they must have different names.

因此,您要么必须使用不同的临时 table 名称,要么必须在存储过程之外执行此操作并使用 GO.

对于脚本,正如其他人所说,使用 GO 是解决方法。

但是,如果这实际上是存储过程中的代码,您就会遇到不同的问题。不喜欢语法的不是 SSMS,而是 SQL 编译器。它看到并阻塞了这三个 INSERT… INTO… 语句,并且不够聪明,无法意识到您正在删除创建语句之间的 table。 (即使你去掉了IF语句,你仍然会遇到问题。)

解决方法是使用不同的临时 table 名称。 (附带好处,因为 temp table 基于三个不同的 table,这将有助于更清楚地表明 table 结构是不同的。)如果您担心过度 space 在内存中,您仍然可以在完成后删除每个临时文件 table。