下面的代碼工作正常,而且相當精確,但可以像這樣對待其他「標準」方式嗎?使用try-catch模塊在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)
下面的代碼工作正常,而且相當精確,但可以像這樣對待其他「標準」方式嗎?使用try-catch模塊在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)
這是更好地使用
If Object_Id('Tempdb..#temp') Is Not Null
Drop Table #temp
create table #temp
當你打算最終創造出#TEMP表不需要嘗試捕捉,得到#TEMP表不存在
一個錯誤信息如果create語句是在try裏面,它可能有一些用處
爲什麼?我不一定不同意,但你能解釋這種方法提供的好處嗎? –
Hi @ destination-data,通過問題中代碼的外觀,anonxen最終希望創建一個臨時表,它不需要try catch給出tempTable不存在的錯誤消息,以防創建語句爲在嘗試中,它可能有一些使用 – Pream
如果你的答案包括描述,我肯定會贊成它。 –
使用EXISTS
語句,IF
表存在的話只有drop表。否則直接創建 表:
BEGIN TRY
IF Object_Id('Tempdb..#temp') Is Not Null
DROP Table #temp
CREATE table #temp
END try
BEGIN CATCH
PRINT 'table does not exist'
END CATCH
這一切都取決於您的要求。如果你只是在臨時桌旁工作,那麼Pream的答案就和任何一個一樣好。你的技巧會反饋表是否存在,並且反饋可能是有用的 –
如果你打算在發生異常時採取行動,捕獲塊是非常明智的。如果沒有額外的動作,你可能會認爲這只是額外的輸入。在這種情況下,我經常不在乎臨時存在與否。我只是檢查以避免錯誤。考慮到這一點,'IF NOT EXISTS/OBJECT_ID IS NULL'方法更加簡潔。 –
@ destination-data看起來像「Try catch」在這裏是過度殺傷。如果在表不存在的情況下需要額外的操作,如果...開始附加動作結束。 – Serg