使用 try-catch 块删除 Sql-Server 中的表

ano*_*xen 3 sql t-sql sql-server

下面的代码有效并且非常精确,但是与其他“标准”方式相比,这样做可以吗?

--Drop table if exists
begin try
    drop table #temp
end try

begin catch 
    print 'table does not exist'
end catch

--Create table
create table #temp(a int, b int)
Run Code Online (Sandbox Code Playgroud)

Pre*_*eam 5

最好使用

If Object_Id('Tempdb..#temp') Is Not Null
Drop Table #temp
create table #temp
Run Code Online (Sandbox Code Playgroud)

当您打算最终创建一个 #temp 表时,它不需要 try catch 来给出 #temp 表不存在的错误消息

如果 create 语句在 try 中,它可能有一些用处