微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQLServer资源是否存在汇总

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'


扩展知识:

object_id()可接受两个参数,第一个如上所示,代表资源的名称,上面的就是表的名字,但往往我们要说明我们所要创建的是什么类型的资源, 
这样sql可以明确地在一种类型的资源中查找是否有重复的名字,如下: 
    if   object_id('tb_table','u') is not null  
        print 'exist' 
    else 
        print'not exist' 
第二个参数 "u" 就表示tb_table是用户创建的表,即:USER_TABLE地首字母简写 
查询sys.objects中可得到各种资源的类型名称(TYPE列),这里之举几个主要的例子 

u  -----------  用户创建的表,区别于系统表(USER_TABLE) 

s  -----------  系统表(SYstem_TABLE) 

v  -----------  视图(VIEW) 

p  -----------  存储过程(sql_STORED_PROCEDURE) 

可使用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




版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐