object_id()函數

SQLServer數據庫中,若是查詢數據庫中是否存在指定名稱的索引或者外鍵約束等,常常會用到object_id('name','type')方法,作筆記以下:數據庫

?ide

語法:object_id('objectname')或object('objectname','type')函數

做用:該函數會返回指定對象的ID值,能夠在sysobjects表中進行驗證。ui

其中objectname數據類型爲 char 或 nchar。若是 object 的數據類型是 char,那麼隱性將其轉換成 nchar。spa

type以下列表:scala

V = View
U = Table (user-defined)
P = SQL Stored Procedure


AF = Aggregate function (CLR)
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
FN = SQL scalar function
FS = Assembly (CLR) scalar-function
FT = Assembly (CLR) table-valued function
IF = SQL inline table-valued function
IT = Internal table
PC = Assembly (CLR) stored-procedure
PG = Plan guide
PK = PRIMARY KEY constraint
R = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S = System base table
SN = Synonym
SQ = Service queue
TA = Assembly (CLR) DML trigger
TF = SQL table-valued-function
TR = SQL DML trigger
UQ = UNIQUE constraint
X = Extended stored procedure對象

例子以下:索引

select object_id('fk_xxx_xx','F')會取出約束名爲fk_xxx_xx的ID值,如返回144444444這個值。get

上面的語句等同:io

select ID from sysobjects where name='fk_xxx_xx' and type='F'

======================================================================================= 

你們都知道在數據庫中有一個系統表sysobjects,裏面存儲了數據庫各個對象的信息。能夠查詢下看看結果。能夠看出每一個對象都有一個ID,這個表存儲了表,存儲過程,觸發器,視圖等相關信息。注意:字段沒有。

  object_id就是根據對象名稱返回該對象的id.
  object_name是根據對象id返回對象名稱.
 

  select object_id(對象名)等同於:
  select id from sysobjects where name=對象名

  select object_name(id號)等同於:
  select name from sysobjects where id=id號

======================================================================================= 

判斷臨時表

if object_id(N'tempdb..#ABC',N'U') is  null

tempdb是SQL Server的系統數據庫一直都是SQLServer的重要組成部分,用來存儲臨時對象。能夠簡單理解tempdb是SQLServer的速寫板。應用程序與數據庫均可以使用tempdb做爲臨時的數據存儲區。一個實例的全部用戶都共享一個Tempdb。

相關文章
相關標籤/搜索