SQL常用命令之判断数据库、函数、存储过程、表、视图等是否存在

SQLServer判断 数据库 函数 存储过程 表 视图等 是否存在

1、判断数据库是否存在
if exists(select * from master..sysdatabases where name=N'数据库名')
print 'The database exists' --若存在则输出
--drop database '数据库名' --用于最初创建数据库
else
print 'not exists'

2、判断要创建的函数名是否存在
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[函数名]') and xtype in (N'FN',N'IF',N'TF'))
--drop function [dbo].[函数名]
go

3、判断存储过程是否存在
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[存储过程名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
--drop procedure [dbo].[存储过程名]
GO

4、判断表是否存在
if exists (select * from dbo.sysobjects where id=object_id(N'[dbo].表名') and OBJECTPROPERTY(id,N'IsUserTable') = 1)
print 'The UserTable exists'
--drop table[dbo].[表名]
go

5、判断临时表是否存在
if  object_id('Tempdb.dbo.#Test') is not null
begin
print 'exists'
end
begin
print 'not exists'
end

6、判断表中的列名是否存在

if col_length('表名','列名') is null
print 'not exists'
else
print 'The column exists'

select 1 from sysobjects where id in (select id from syscolumns where name='列名') and name='表名'

7、判断视图是否存在
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[视图名]') and OBJECTPROPERT(id,N'IsView') = 1)
print 'The View exists'
--drop view [dbo].[视图名]
go

8、判断触发器是否存在
if exists(select * from dbo.sysobjects where id = object_id(N'[dbo].[触发器名]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
print 'The Trigger'
--drop trigger [dbo].[触发器名]
go

备注:
    object_id:返回数据库对象标识号。
    N:将非unicode字符转成unicode字符,它来自 SQL-92 标准中的National(Unicode)数据库类型,用于扩展和标准化。
    以上的查询方式也可以使用下面这种方式进行
    select * from dbo.sysobjects where  xtype in (N'FN',N'IF',N'TF')
    xtype:表示参数类型。
参数类型种类:
    'FN':Scalar-valued-Function 标量值函数 ,
    'IF':内嵌表函数,
    'TF':Table-valued-Function 表值函数 ,
    'C':CHECK约束 ,
    'D':默认值或DEFAULT约束,
    'F':FOREIGNKEY约束 ,
    'L':日志 ,
    'P':存储过程
    'PK':PRIMARYKEY约束(类型是K)
    'RF' 复制筛选存储过程
    'S':系统表
    'TR':触发器
    'U':用户表
    'UQ':UNIQUE约束(类型是K)
    'V':视图
    'X':扩展存储过程

 

 

 

 

 

 

 

 


 

posted @ 2013-05-17 09:45  Shang0109  阅读(807)  评论(0编辑  收藏  举报