我的SQL Server框上有许多以前缀zzz
开头的数据库。
有没有办法执行删除和删除数据文件的DROP DATABASE
(或其他方法)?如果打开了连接,我希望它关闭。
基本上我只是希望他们消失。
答案 0 :(得分:2)
生成放置脚本,复制/粘贴&运行:
exec master.sys.sp_msforeachdb 'if ''?'' like ''ZZZ%'' print ''drop database [?]'''
如果勇敢的话,直接删除SQL字符串。
答案 1 :(得分:1)
您可以编写动态SQL来执行此操作:
use master
go
declare @dbnames nvarchar(max)
declare @statement nvarchar(max)
declare @closeconnection nvarchar(max)
set @dbnames = ''
set @statement = ''
select @dbnames = @dbnames + ',[' + name + ']' from sys.databases where name like 'zzz%'
if len(@dbnames) = 0
begin
print 'no databases to drop'
end
else
BEGIN
SET @closeconnection = 'alter database ' + substring(@dbnames, 2, len(@dbnames))
+ ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE'
set @statement = 'drop database ' + substring(@dbnames, 2, len(@dbnames))
print @statement
EXEC sp_executesql @closeconnection;
exec sp_executesql @statement;
end
通常,关闭与数据库的所有活动连接的语法是:
--set it to single user to disable any other connections
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do your stuff here
--set it back to multiple users
ALTER DATABASE YourDatabase SET MULTI_USER
或者,您也可以生成一个动态选择列表,用于填充drop数据库语句以及如下所示的紧密连接语句:
USE master;
Go
SELECT 'DROP DATABASE '+ name,
'alter database ' + name + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE'
FROM sys.databases WHERE name like 'zzz%';
GO
答案 2 :(得分:1)
use master;
go
- 这会丢弃所有以t5开头的dbs ....
declare @strsql varchar(500)
declare @curname sysname
select @curname = name from sys.databases
where name like 't5%'
while( @@rowcount> 0)
begin
set @strsql ='ALTER DATABASE ' +@curname +' SET OFFLINE WITH ROLLBACK IMMEDIATE'
exec (@strsql)
set @strsql ='drop database '+@curname
exec (@strsql)
select @curname = name from sys.databases
where name like 't5%'
end
答案 3 :(得分:0)
我修改了benjamin的脚本,所以你只需要声明一次前缀。
use master;
declare @dbPrefix varchar(10)
set @dbPrefix = 'zzz_%';
declare @strsql varchar(500)
declare @curname sysname
select @curname = name from sys.databases
where name like @dbPrefix
while( @@rowcount> 0)
begin
set @strsql ='ALTER DATABASE ' +@curname +' SET SINGLE_USER WITH ROLLBACK IMMEDIATE'
exec (@strsql)
set @strsql ='drop database '+@curname
exec (@strsql)
select @curname = name from sys.databases
where name like @dbPrefix
end