Kill All Active Connections To A Database

本文介绍了一种在 SQL Server 中立即或定时关闭所有数据库连接的方法。通过使用 ALTER DATABASE 命令设置 SINGLE_USER 模式,可以确保没有新的连接,并在完成维护任务后恢复到 MULTI_USER 模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://wiki.lessthandot.com/index.php/Kill_All_Active_Connections_To_A_Database

Jump to: navigation , search

To kill all the connections to your database you can use the ALTER DATABASE command. Sometimes you want to restore the database from a backup but can't because people are connected. Here is one way which will kick off all the users immediately

 

  1. ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
  2.  
  3. --do you stuff here
  4.  
  5. ALTER DATABASE YourDatabase SET MULTI_USER


The code below will wait 60 seconds

  1. ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK AFTER 60 SECONDS
  2.  
  3. --do you stuff here
  4.  
  5. ALTER DATABASE YourDatabase SET MULTI_USER

The reason this is better than looping over sysprocesses or sys.dm_exec_sessions is that nobody will connect while that looping piece of code runs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值