Kill All User Sessions in a SQL Server Database

Kills every user session in one database, for example before a restore. Set the database name and run it first with @Apply = 0 to see the KILL commands it would run; set @Apply = 1 to run them. Your own session is skipped. Works on SQL Server 2016 to 2022 and later.

-- Kill all user sessions in one database (SQL Server 2016-2022)
-- Set the database name, run once with @Apply = 0 to see what would be killed.
USE [master];

DECLARE @DatabaseName sysname = N'MyDB';
DECLARE @Apply bit = 0;
DECLARE @kill nvarchar(max) = N'';

SELECT @kill += N'KILL ' + CONVERT(nvarchar(10), s.session_id) + N';' + CHAR(13) + CHAR(10)
FROM sys.dm_exec_sessions AS s
WHERE s.database_id = DB_ID(@DatabaseName)
  AND s.is_user_process = 1
  AND s.session_id <> @@SPID;

IF @Apply = 1
    EXEC sys.sp_executesql @kill;
ELSE
    PRINT @kill;

-- Quicker alternative: throw everyone out and roll back their work
-- ALTER DATABASE [MyDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
-- ALTER DATABASE [MyDB] SET MULTI_USER;