-- SQL SERVER 判断是否存在某个触发器、储存过程
-- 判断储存过程,如果存在则删除
IF (EXISTS(SELECT * FROM sysobjects WHERE name='procedurename' AND type='P'))
DROP PROCEDURE procedurename
-- 判断触发器,如果存在则删除
IF (EXISTS(SELECT * FROM sysobjects WHERE id=object_id(N'[dbo].[triggername]') AND OBJECTPROPERTY(id, N'IsTrigger') = 1))
DROP TRIGGER triggername
-- 判断用户函数是否存在,如果存在则删除
-- 此处type有两种: 'TF'- Table-Value Function 表值函数 'FN'- Scalar-Value Function 标量值函数
IF (EXISTS(SELECT * FROM sysobjects WHERE id=object_id(N'[dbo].[userfunction]') AND (type='FN' OR type='TF')))
DROP FUNCTION userfunction
-- 判断视图是否存在,存在则删除
IF (EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME=N'viewname'))
DROP VIEW viewname
-- 判断用户表 是否存在,若存在则删除
IF (EXISTS(SELECT * FROM sysobjects WHERE id=N'tablename' AND OBJECTPROPERTY(id, N'IsUserTable')=1))
DROP TABLE tablename
-- 判断数据库,如果存在则删除
IF (EXISTS(SELECT * FROM master.dbo.sysdatabases WHERE dbid=db_ID('dbname')))
DROP DATABASE dbname
-- 如果提示:删除数据库时提示数据库正在被使用,无法删除(Cannot drop database databasename because it is currently in use),使用:
IF (EXISTS(SELECT * FROM master.dbo.sysdatabases WHERE dbid=db_ID('dbname')))
BEGIN
USE master
ALTER DATABASE dbname
SET single_user
WITH ROLLBACK IMMEDIATE
DROP DATABASE dbname
END