-- Script to Detach All User Databases SET NOCOUNT ON DECLARE @dbName varchar(80), @ServerName varchar(20) SELECT @ServerName = @@servername DECLARE dbCursor CURSOR FOR SELECT name FROM master.dbo.sysdatabases WHERE name NOT IN ( 'model', 'master', 'msdb', 'tempdb', 'distribution', 'repldata' ) OPEN dbCursor FETCH NEXT FROM dbCursor INTO @dbName IF ( @@FETCH_STATUS <> 0 ) PRINT 'No User databases found!!!' WHILE ( @@FETCH_STATUS = 0 ) BEGIN DECLARE @SQLStr varchar(8000) SET @SQLStr = 'DECLARE @SPIDStr varchar(8000), @ConnKilled smallint SELECT @ConnKilled = 0 @SPIDStr = '''' SELECT @SPIDStr = coalesce( @SPIDStr, '', '' ) + ''KILL '' + convert( varchar, spid ) + ''; '' FROM master.dbo.sysprocesses WHERE dbid = db_id( ''' + @dbName + ''' ) IF LEN( @SPIDStr ) > 0 BEGIN EXECUTE( @SPIDStr ) SELECT @ConnKilled = COUNT(1) FROM master..sysprocesses WHERE dbid = db_id( ''' + @dbName + ''' ) END' + char(10) + ';' + char(10) + 'EXECUTE sp_detach_db ' + @dbName EXECUTE ( @SQLStr ) PRINT 'Detach of ' + upper( @dbName ) + ' Database Successfully Completed' PRINT '' FETCH NEXT FROM dbCursor INTO @dbName END CLOSE dbCursor DEALLOCATE dbCursor PRINT ' ' PRINT upper( @ServerName ) + ' --> All User Databases Successfully Detached'
Another method:-
set nocount on declare @dbname as varchar(80) declare @server_name as varchar(20) select @server_name = @@servername declare rs_cursor CURSOR for select name from master.dbo.sysdatabases where name not in ('model','master','msdb','tempdb','alert_db','mssecurity') open rs_cursor Fetch next from rs_cursor into @dbname IF @@FETCH_STATUS <> 0 PRINT 'No database to backup...Please check your script!!!' WHILE @@FETCH_STATUS = 0 BEGIN print 'sp_detach_db ' + @dbname print 'go' print 'print ''Detach of ' + upper(@dbname) + ' database successfully completed''' print 'go' PRINT ' ' FETCH NEXT FROM rs_cursor INTO @dbname END CLOSE rs_cursor deallocate rs_cursor print ' ' print 'print ''SERVER NAME : ' + upper(@server_name) + '--> All databases successfully detached'''
No comments:
Post a Comment