SQL Server 批量删除指定数据库
程序员文章站
2022-05-10 23:25:56
...
批量删除指定数据库。
比如我想要删除数据库名字中包含 “vivi”的所有数据库:
if object_id('tempdb..#dbToDelete') is not null
drop table #dbToDelete
if object_id('tempdb..#databaseName') is not null
drop table #databaseName
declare @dbToDelete table(name varchar(50))
declare @databaseName varchar(100)
--insert into @dbToDelete select name from Master..SysDatabases where name like '%vivi%'
insert into @dbToDelete select name from sys.databases where name like '%vivi%'
while exists(select name from @dbToDelete)
begin
select top 1 @databaseName=name from @dbToDelete
if exists(select * from sys.databases where name = @databaseName)
begin
print 'dropping databse: '[email protected]
--强制删除所有符合条件的实例
exec('
use master
ALTER DATABASE ' + @databaseName +' SET SINGLE_USER WITH ROLLBACK IMMEDIATE
drop database '[email protected])
end
delete from @dbToDelete where name = @databaseName
end
上一篇: redis源代码分析19–主从复制
下一篇: 大前端笔记02