close existing connections during a restore is there an option to close existing connections when doing a database restore in transact sql (equivalent to the box that we can check in SSMS)?

can we use with restricted user to do it an if so, what should we do to remove this option once the restore operation finish

Thanks in advance
You will have to set the database to single user with roll back immediate, do the restore , then set to multi user in the same batch

ALTER DATABASE [test] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE [test] FROM  DISK = N'V:\MSSQL2016\Backup\test.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
ALTER DATABASE [test] SET MULTI_USER


You could get this script by setting all your options in SSMS and instead of clicking OK, Click Script at the top of the window.