T SQL判斷是否存在表 臨時表

2022-02-06 11:16:27 字數 1064 閱讀 4938

利用sql server的系統函式 object_id() 可以判斷是否存在表、臨時表,

object_id() 的作用是返回架構範圍內物件的資料庫物件標識。(即返回系統檢視  sys.objects 的 object_id 字段值)

object_id ( '

[ database_name . [ schema_name ] . | schema_name . ]

object_name'[

,'object_type'

] )

返回值是 int 型別,如果物件不存在則返回 null 。

if

object_id(n'

dbo.info_city

',n'

u') is

notnull

print

'存在表

'else

print

'不存在表

'

if

object_id(n'

tempdb.dbo.#temp2

',n'

u') is

notnull

print

'存在#temp2

'else

print

'不存在#temp2

'

注意:判斷臨時表需要指定臨時資料庫 tempdb 

因為函式object_id() 返回的是架構範圍內物件的資料庫物件標識,意味著例如表、檢視、約束、儲存過程等其他架構範圍內物件也可以通過上述方法判斷其存在性。

例如,判斷儲存過程僅需稍稍修改物件名和物件型別即可:

if

object_id(n'

dbo.p_base_getserverinfo

',n'

p') is

notnull

print

'存在儲存過程

'else

print

'不存在儲存過程

'

判斷臨時表是否存在

if object id tempdb.t is not null drop table t if objectproperty object id tempdb.t istable 1 print authors is a table else if objectproperty object i...

判斷臨時表是否存在 臨時表的刪除

以下是在網上搜尋的乙個說明 臨時表有兩種型別 本地和全域性。它們在名稱 可見性以及可用性上有區別。本地臨時表的名稱以單個數字符號 打頭 它們僅對當前的使用者連線是可見的 當使用者從 sql server 例項斷開連線時被刪除。全域性臨時表的名稱以兩個數字符號 打頭,建立後對任何使用者都是可見的,當所...

判斷MS SQLSERVER臨時表是否存在

drop table tempcitys select into tempcitys from hy citys 上面的語句第一次執行的時候就肯定出錯了,但第二次就不會。因為select into tempcitys from hy citys自動建立了臨時表 tempcitys 第一次臨時表不存在...