我们可以使用系统表例如sysobjects,sys.databases等等,还可以OBJECT_ID函数;
注意:
使用 OBJECT_ID不能查询非架构范围内的对象(如 DDL触发器)。对于在sys.objects目录视图中找不到的对象,需要通过查询适当的目录视图来获取该对象的标识号。例如,若要返回 DDL 触发器的对象标识号,请使用SELECTOBJECT_ID FROM sys.triggers WHERE name = 'DatabaseTriggerLog'。
下面给出一些直接使用的例子:
1)判断存储过程是否存在
if exists (select * from sysobjects where id =object_id(N'[存储过程名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [存储过程名]
go
或者
IF OBJECT_ID(N'[存储过程名]',N'P') IS NOT NULL
dropprocedure [存储过程名]
go
2)判断数据库是否存在
if exists (select * from sys.databases where name= '[数据库名]')
drop database [数据库名]
go
3)判断表是否存在
if exists (select * fromsysobjects where id = object_id(N'[表名]') and OBJECTPROPERTY(id,N'IsUserTable') = 1)
drop table [表名]
go
或者
IF OBJECT_ID(N'[表名]',N'U') IS NOT NULL
drop table [表名]
go
4)判断视图是否存在
if exists (select * fromsysobjects where id = object_id(N'[视图名]') and OBJECTPROPERTY(id, N'IsView')= 1)
drop view[视图名]
go
或者
IF OBJECT_ID(N'[视图名]',N'V')IS NOT NULL
drop view [视图名]
go
5)判断列名是否存在
if exists(select *from syscolumns where name='[列名]'andid=object_id('[数据库名].[Owner].[表名]'))
select *from [表名]
go
6)判断函数是否存在
IF OBJECT_ID (N'[函数名]')IS NOT NULL
DROP FUNCTION [函数名]
Go
或者
if exists(select* from dbo.sysobjectswhere id = object_id(N'[函数名]')andxtype in(N'FN',N'IF', N'TF'))
drop function [函数名]
go
7)判断表中是否存在索引
if exists(select * fromsysindexes where id=object_id(['表名]') and name='[索引名]')
drop index [索引名]
go
8)判断全文目录是否存在
select * from sysfulltextcatalogswhere name =['全文目录名']
9)判断临时表是否存在
if exists (select * from tempdb..sysobjects where id = object_id(N'tempdb..#临时表名'))
drop table [#临时表名'];
go
或者
if object_id('tempdb..#临时表名') is not null
drop table [#临时表名'];