sql中case when的用法_数据库大师成长日记:SQL中if exists用法总结

经常写SQL脚本的朋友,对if exists肯定非常熟悉,在做删除或更新操作之前,为了保证我们的操作的有效性避免异常的发生,我们习惯于先用if exists做一下判断。

3cdc87066a8d7302c9ceba2875266ad9.png

今天我们就把if exists的各种常用的应用场景做一个总结。

1、判断数据库是否存在

if exists (select * from sys.databases where name = '数据库名')  drop database [数据库名]

2、判断表是否存在

if exists (select * from sysobjects where id = object_id(N'[表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)  drop table [表名]

3、判断存储过程是否存在

if exists (select * from sysobjects where id = object_id(N'[存储过程名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)  drop procedure [存储过程名]

4、判断临时表是否存在

if object_id('tempdb..#临时表名') is not null  drop table #临时表名

5、判断视图是否存在

--SQL Server 2000 IF EXISTS (SELECT * FROM sysviews WHERE object_id = '[dbo].[视图名]' --SQL Server 2005及之后 IF EXISTS (SELECT * FROM sys.views WHERE object_id = '[dbo].[视图名]' 

6、判断自定义函数是否存在

-- 判断要创建的函数名是否存在

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

7、判断列是否存在

if exists(select * from syscolumns where id=object_id('表名') and name='列名')  alter table 表名 drop column 列名

8、判断列是否自增列

if columnproperty(object_id('table'),'col','IsIdentity')=1  print '自增列' else  print '非自增列' 

9、判断表中是否存在索引

if exists(select * from sysindexes where id=object_id('表名') and name='索引名')  print '存在索引' else  print '不存在索引'

希望对您有所帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值