Skip Navigation LinksDiscussions List : Drop multiple user databases

Started: 8/18/2019 10:41 PM
Picture Placeholder: Zahid Ahamed
Picture Placeholder: Zahid Ahamed
  • Zahid Ahamed

### Drop multiple user databases

​SET NOCOUNT ON
GO
DECLARE @dbName       NVARCHAR (255);
DECLARE @SqlStatement     NVARCHAR(4000);

DECLARE databaseCurs CURSOR FOR
      SELECT name FROM sys.databases WITH (NOLOCK)
      WHERE name NOT IN ('tempdb','model', 'master', 'msdb')
      OPTION (RECOMPILE);

OPEN databaseCurs;   
FETCH NEXT FROM databaseCurs INTO @dbName
WHILE (@@fetch_status <> -1)
BEGIN
 IF (@@fetch_status <> -2)
 BEGIN
  SET @SqlStatement = N'ALTER DATABASE [' + @dbName + N']' + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' + N'DROP DATABASE [' + @dbName + N'];';
 ----SET @SqlStatement = N'BACKUP LOG [' + @dbName + N'] TO DISK = ''S:\BACKUP\' + @dbName + N'.BAK'''; (For Transaction Log Backup)
  EXECUTE sp_executesql @SqlStatement

  --print @SqlStatement
  PRINT N'drop database completed suceessfully: ' + @dbName
 END;
 FETCH NEXT FROM databaseCurs INTO @dbName;
END;
CLOSE databaseCurs;
DEALLOCATE databaseCurs;
GO

Picture Placeholder: Zahid Ahamed
  • Zahid Ahamed
/_layouts/15/images/person.gif" alt="Picture Placeholder: Zahid Ahamed" />
Zahid Ahamed

​SET NOCOUNT ON
GO
DECLARE @dbName       NVARCHAR (255);
DECLARE @SqlStatement     NVARCHAR(4000);

DECLARE databaseCurs CURSOR FOR
      SELECT name FROM sys.databases WITH (NOLOCK)
      WHERE name NOT IN ('tempdb','model', 'master', 'msdb')
      OPTION (RECOMPILE);

OPEN databaseCurs;   
FETCH NEXT FROM databaseCurs INTO @dbName
WHILE (@@fetch_status <> -1)
BEGIN
 IF (@@fetch_status <> -2)
 BEGIN
  SET @SqlStatement = N'ALTER DATABASE [' + @dbName + N']' + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' + N'DROP DATABASE [' + @dbName + N'];';
 ----SET @SqlStatement = N'BACKUP LOG [' + @dbName + N'] TO DISK = ''S:\BACKUP\' + @dbName + N'.BAK'''; (For Transaction Log Backup)
  EXECUTE sp_executesql @SqlStatement

  --print @SqlStatement
  PRINT N'drop database completed suceessfully: ' + @dbName
 END;
 FETCH NEXT FROM databaseCurs INTO @dbName;
END;
CLOSE databaseCurs;
DEALLOCATE databaseCurs;
GO

08/18/2019 10:41 PM8/18/2019 10:41 PMNoGeneral
0
8/18/2019 10:40 PM
There are no items to show in this view of the "Discussions List" discussion board.