MSSQL single user mode and multi user

Date: 2023-01-09
-- enter single user mode
ALTER DATABASE [DatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

-- single user mode can be used for restoring backups
RESTORE DATABASE [DatabaseName] FROM DISK = '{escapedBackupFile}' WITH REPLACE

-- restore multi user mode
ALTER DATABASE [DatabaseName] SET MULTI_USER


-- when database is in restoring state, run next line
RESTORE DATABASE [DatabaseName] WITH RECOVERY


--------------------------------------------------------------------
--   RESTORE DATABASE FROM SINGLE USER WITH EXISTING CONNECTION   --
--------------------------------------------------------------------

-- list connections
EXEC sp_who
 
-- kill process (connection):
KILL <pid>

-- restore multi user mode
ALTER DATABASE [DatabaseName] SET MULTI_USER
71750cookie-checkMSSQL single user mode and multi user