gpt4 book ai didi

sql-server - 为什么 DROP TABLE 在 SELECT INTO 之前似乎没有生效?

转载 作者:行者123 更新时间:2023-12-03 02:58:19 25 4
gpt4 key购买 nike

以下 tSQL 查询令我困惑:

select 1 as FIELD into #TEMP
drop table #TEMP
select 1 as FIELD into #TEMP

当我从 SQL Server Management Studio session 窗口运行它时(对整个查询按 F5 作为一个组),我收到以下错误:

Msg 2714, Level 16, State 1, Line 3
There is already an object named '#TEMP' in the database.

请注意,在执行查询之前,表#TEMP并不存在。

我认为代码不应该产生任何错误,因为第 2 行正在删除临时表。但执行第 3 行时,好像 drop 并未生效。

我的问题:

  1. 为什么会发生错误?
  2. 如何修复查询,使其按预期执行?
PS。上面的查询是我的现实世界查询的简化,它显示出相同的症状。

PS2。不管这是否是一个合理的编程实践(正如 Sean 在他的评论中暗示的那样),这种意想不到的行为促使我寻找有关如何解析这些查询的信息,希望这些知识将来对我有所帮助。

最佳答案

我发现现有表的查找是不同的:

select 1 as FIELD into #TEMP
drop table #TEMP

当您在这些命令之后使用 into 语句时:

select 1 as FIELD into #TEMP

错误是:

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

当您在这些命令之后对 #TEMP 使用 select 时:

select * from #TEMP

错误是:

Invalid object name '#TEMP'.

因此,在第一种情况下,存在一个名称为 #TEMP 的对象,而在另一种情况下,则不存在名称为 #TEMP 的对象!

来自 technet.microsoft 的重要说明是:

DROP TABLE and CREATE TABLE should not be executed on the same table in the same batch. Otherwise an unexpected error may occur.

<小时/>

在通过 SQL Server 数据库引擎删除表的注释中:

The SQL Server Database Engine defers the actual page deallocations, and their associated locks, until after a transaction commits.

因此,使用 select 语句的第二个错误可能与实际页面释放有关,而使用 into 语句的第一个错误可能与关联锁到事务提交之间的持续时间

关于sql-server - 为什么 DROP TABLE 在 SELECT INTO 之前似乎没有生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com