我正在尝试以下查询
if exists (select 1 from emp where eid = 6)
begin
if object_id('tempdb..#columntable') is not null
begin
drop table #columntable
end
create table #columntable (oldcolumns varchar(100))
end
else
begin
if object_id('tempdb..#columntable') is not null
begin
drop table #columntable
end
create table #columntable (newcolumns varchar(100))
end
但我收到错误
Msg 2714, Level 16, State 1, Line 8
There is already an object named '#columntable' in the database.
谁能建议为什么?如果我不写 else 部分,同样的查询工作正常。
最佳答案
临时表不会在查询结束时自动删除,只有在当前与数据库的连接被删除或您使用 DROP TABLE #columntable
显式删除它们时才会删除。
在查询开始时测试表是否存在或始终在最后删除它(最好是两者)
编辑:正如 Matrin 在他的评论中所说,这实际上是一个解析错误。如果仅在执行 SQL 时解析 SQL,则会出现相同的错误。
为了测试这一点,我拆分了您的查询并尝试了:
if exists (select 1 from emp where id = 6)
create table #columntable (newcolumns varchar(100))
GO
if not exists (select 1 from emp where id = 6)
create table #columntable (oldcolumns varchar(100))
GO
解析器对此很满意。有趣的是,如果您改为使用非临时表,原始查询可以很好地解析(我意识到会产生问题,我只是想找出查询无法解析的原因)。
关于sql - 数据库中已经有一个名为 '#columntable' 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4245444/