怎么判断sql数据库是否存在,存在删除
2022-09-29 · 百度认证:北京惠企网络技术有限公司官方账号
判断数据库,如果存在则删除:
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
扩展资料
判断储存过程,如果存在则删除
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