object_id用法

时间:2022-08-01 06:57:18
特别是在建表建存储过程的时候进场会写到:

IF OBJECT_ID('Table_Test','U') IS NOT NULL
DROP TABLE Table_Test
这种方式代替了以往所使用的 IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME = 'Table_Test')
DROP TABLE Table_Test
第一段代码中的 U 可以省略不写, 这样系统就会检索所有的对象名称以找到对应的ID, 但是写出来就可以更加明确是哪一种类型,筛选的范围要小很多.
以下列出全部 Object type (加粗的是比较常用的): 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 P = SQL Stored Procedure 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 TT = Table type U = Table (user-defined) UQ = UNIQUE constraint V = View X = Extended stored procedure 可以通过这个查询语句获取当前数据库中各个数据库表,视图,存储过程等数量。 SELECT CASE TYPE
WHEN 'U' THEN 'User Defined Tables'
WHEN 'V' THEN 'View'
WHEN 'S' THEN 'System Tables'
WHEN 'IT' THEN 'Internal Tables'
WHEN 'P' THEN 'Stored Procedures'
WHEN 'PC' THEN 'CLR Stored Procedures'
WHEN 'X' THEN 'Extended Stored Procedures'
WHEN 'FN' THEN 'Scalar-valued Functions'
WHEN 'IF' THEN 'Table-valued Functions'
END AS Objects,
COUNT(*) AS Counts
FROM SYS.OBJECTS
WHERE TYPE IN ('U','V','S','IT','P','PC','X','FN','IF')
GROUP BY TYPE