在开始尝试开始捕获块中删除表 - 是否有任何性能损失?

Mar*_*lli 1 sql-server dynamic-sql sql-server-2008-r2 error-handling temporary-tables

下面的代码是一个动态 sql,它将为您提供系统中所有警报的列表。

有用。

出于这个问题之外的原因,代码中有一个临时表。

这个问题与我在创建临时表之前确保临时表不存在的方式有关。

我在 try catch 块中放置了一个删除表,如下面的代码所示。

我的问题是:

  • 有没有性能损失?
  • 这样做有什么缺点吗?
  • 为什么这不被视为通常的最佳实践?

我仍然有一些服务器 sql-server-2008-r2 但大多数我的服务器是 sql server 2016。

EXEC Sp_executesql 
N'  

begin try
 drop table #tmp_sp_help_alert 
end try
begin catch
end catch

create table #tmp_sp_help_alert  (
id int null, name nvarchar(128) null,  
event_source nvarchar(100) null, 
event_category_id int null, 
event_id int null, 
message_id int null,  
severity int null, 
enabled tinyint null, 
delay_between_responses int null, 
last_occurrence_date int null, 
last_occurrence_time int null, 
last_response_date int null, 
last_response_time int null, 
notification_message nvarchar(512) null, 
include_event_description tinyint null, 
database_name nvarchar(128) null, 
event_description_keyword nvarchar(100) null, 
occurrence_count int null, 
count_reset_date int null, 
count_reset_time int null, 
job_id uniqueidentifier null, 
job_name nvarchar(128) null, 
has_notification int null, 
flags int null, 
performance_condition nvarchar(512) null, 
category_name nvarchar(128) null,  
wmi_namespace nvarchar(max) null,  
wmi_query nvarchar(max) null, 
type int null)   

insert into #tmp_sp_help_alert 
exec msdb.dbo.sp_help_alert         



SELECT * FROM #tmp_sp_help_alert AS tsha --WHERE (tsha.name=@_msparam_0)   
--drop   table #tmp_sp_help_alert

', 
    N'@_msparam_0 nvarchar(4000)', 
    @_msparam_0=N'SQLPROD2 Alert - AG Role Change' 
Run Code Online (Sandbox Code Playgroud)

spa*_*dba 5

最好检查表是否存在,而不是试图删除它并忽略任何错误。在所有编程语言中,这通常被认为是一种不好的做法。在 SQL Server 和所有 RDBMS 中,您都有元数据,因此当然有更好的方法来做到这一点。

一个例子:

IF OBJECT_ID('tempdb..#tmp_sp_help_alert') IS NOT NULL
    DROP TABLE #tmp_sp_help_alert;
Run Code Online (Sandbox Code Playgroud)

此外,临时表在超出范围时会自动删除(对于本地临时表,当过程结束时),因此测试表是否存在可能会有些过头。出于同样的原因,也可能没有必要删除作用域末尾的表。