sql - 使用 try-catch block 在 Sql-Server 中删除表

标签 sql sql-server tsql

下面的代码可以工作并且非常精确,但是与其他“标准”方法相比,这样做是否可以?

--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)

最佳答案

最好用

If Object_Id('Tempdb..#temp') Is Not Null
Drop Table #temp
create table #temp

因为你打算最终创建一个#temp Table,它不需要try catch来给出#temp Table不存在的错误消息

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

关于sql - 使用 try-catch block 在 Sql-Server 中删除表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622818/

相关文章:

c# - C# 如何获取更新记录的ID

sql-server - 日期差异表现

sql - 如何使sql搜索查询更强大?

mysql - Cassandra 的模式和 RDBMS 模式的区别

php - 使用简单的 JOIN

c# - Linq 获得前 9 组加上所有其他组的总和作为第 10 组

sql-server - 异构查询需要 ANSI_NULLS

sql-server - 将 Excel 与 SQL Server 集成

mysql - SQL 查询检查列是否包含某些数据

sql - 带有 RETURNS TABLE(id integer) 返回所有 NULL 的 PostgreSQL 存储过程