1、判断数据库是否存在
使用资源:“master..sysdatabases”存放着所有数据库的信息
判断案例:
if exists(select * from master..sysdatabases where name=N'库名')
print 'exists'
else
print 'not exists'
2、判断数据表是否存在
使用资源:“dbo.sysobjects ”存放着所有数据表的信息
判断案例:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[表名] -- 删除表
3、判断临时表是否存在
使用资源:“tempdb..sysobjects”/"tempdb.dbo.sysobjects"存放着所有临时表的信息
判断案例:
if exists (select * from tempdb..sysobjects where id = object_id(N'tempdb..#临时表名') )
drop table #临时表名 -- 删除临时表
4、object_id()方法实现方便快速地判断
判断案例:
--if object_id('tb_table') is not null --临时表判断
if object_id('tb_table') is not null --正式表判断
print 'exist'
else
print'not exist'
扩展知识:
u
s
v
p
可使用select distinct type ,type_desc from sys.objects 获得全部信息
5、判断表中列是否存在
判断案例:
IF COL_LENGTH( '表名','列名') IS NULL
PRINT 'not exists'
ELSE
PRINT 'exists'
6、判断视图是否存在
判断案例:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[视图名]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[视图名] -- 删除视图
7、判断存储过程是否存在
判断案例:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[存储过程名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[存储过程名] -- 删除存储过程
5、判断方法是否存在
判断案例:
--if exists (select * from sysobjects where xtype='fn' and name='函数名')
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[函数名]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[函数名] -- 删除函数
链接:http://blog.sina.com.cn/s/blog_6d2675450101b6fq.html