gpt4 book ai didi

sql - 为什么我不能在 T-SQL 中重用临时表?

转载 作者:行者123 更新时间:2023-12-03 01:59:20 24 4
gpt4 key购买 nike

这是一些示例代码:

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

create table #TempList (
ID int,
Name varchar(20)
)

insert into #TempList values (1, 'Alpha')
insert into #TempList values (2, 'Beta')
insert into #TempList values (3, 'Gamma')
insert into #TempList values (4, 'Delta')
insert into #TempList values (5, 'Omega')

select * from #TempList

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

create table #TempList (
ID_New int,
AnotherID int,
Name_New varchar(40)
)

insert into #TempList values (100, 110, 'Orange')
insert into #TempList values (101, 111, 'Red')
insert into #TempList values (102, 112, 'Purple')
insert into #TempList values (103, 113, 'Blue')
insert into #TempList values (104, 114, 'Green')

select * from #TempList

这会产生以下错误:

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

我是否无法在同一个 SQL 脚本中重复使用相同的临时表名称?有没有办法重复使用相同的临时表名称?

谢谢。

最佳答案

改变

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

create table #TempList (

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

GO;

create table #TempList (

SQL Server 查询优化器变得困惑。

它看到您第二次创建同一个表。
请注意,表删除(以及创建)具有概率结果,
结果只有在运行时才知道(不是基于语法控制或查询执行计划创建,即 SQL Server 行话中的“编译”)

关于sql - 为什么我不能在 T-SQL 中重用临时表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4216357/

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