我们有一个使用 SQL 服务器的应用程序。此应用程序使用单用户模式非常频繁地恢复数据库。以下是在单用户模式下恢复数据库并在多用户模式下恢复数据库所执行的 SQL。
alter database [test-db] set single_user with rollback immediate;
use master;restore database [test-db] from database_snapshot = 'snapshot_test-db';
alter database [test-db] set multi_user;
将 test-db 切换到单用户模式后,Taskmanager 的一些 4-5 个后台进程跳入,应用程序不再能够使用同一会话对数据库执行进一步的操作(恢复数据库和更改数据库)。这些后台进程在它们之间是死锁的。请参考下面 sp_who2 的输出。
13 ,BACKGROUND ,sa, ., .,master,BRKR EVENT HNDLR,0,27,11/28 16:13:40, ,13 ,0
14 ,BACKGROUND ,sa, ., .,master,BRKR TASK ,0, 0,11/28 16:13:40, ,14 ,0
15 ,sleeping ,sa, ., .,master,TASK MANAGER ,0,2,11/28 16:13:40, ,15 ,0
16 ,BACKGROUND ,sa, .,23 ,test-db,TASK MANAGER ,16,5,11/28 16:13:40, ,16 ,0
17 ,BACKGROUND ,sa, ., .,master,BRKR TASK ,0,0, 11/28 16:13:40, ,17 ,0
18 ,BACKGROUND ,sa, ., .,master,BRKR TASK ,0,36,11/28 16:13:40, ,18 ,0
19 ,sleeping ,sa, ., .,master,TASK MANAGER ,0,0 ,11/28 16:13:40, ,19 ,0
20 ,BACKGROUND ,sa, .,23 ,test-db,TASK MANAGER ,0,1,11/28 16:13:40, ,20 ,0
21 ,背景 ,sa, .,23 ,test-db,TASK MANAGER ,0,1,11/28 16:13:40, ,21 ,0
22 ,BACKGROUND ,sa, ., .,msdb,DELETE ,6094,835, 11/28 16:13:40, ,22 ,0
23 ,BACKGROUND ,sa, .,21 ,test-db,TASK MANAGER ,0,0,11/28 16:13:40, ,23 ,0
24 ,sleeping ,sa, ., .,master,TASK MANAGER ,0 ,0,11/28 16:13:40, ,24 ,0
25 ,sleeping ,sa, ., .,master,TASK MANAGER ,0,0,11/28 16:13:40, ,25 ,0
26 ,睡觉 ,sa, ., .,master,TASK MANAGER ,0,41,11/28 16:13:40, ,26 ,0
27 ,BACKGROUND ,sa, ., .,master,TRACE QUEUE TASK,3047,1680, 11/28 16:13:40, ,27 ,0
28 ,sleeping ,sa, ., .,master,TASK MANAGER ,0,5,11/28 16:13:40, ,28 ,0
29 ,sleeping ,sa, ., .,master,TASK MANAGER ,0,0 ,11/28 16:13:40, ,29 ,0
30 ,sleeping ,sa, ., .,master,TASK MANAGER ,0,0,11/28 16:13:40, ,30 ,0
31 ,sleeping , sa, ., .,master,TASK MANAGER ,0,0,11/28 16:13:40, ,31 ,0
51 ,RUNNABLE ,DY-EPO46\Administrator,DY-EPO46, .,master,SELECT INTO ,110 ,64,11/28 16:30:44,Microsoft SQL Server Management Studio - 查询,51,0
52 ,sleeping ,DY-EPO46\Administrator,DY-EPO46, .,master,AWAITING COMMAND,156,14,11/28 16:16:39,Microsoft SQL Server Management Studio ,52 ,0
53 ,sleeping ,DY-EPO46 \Administrator,DY-EPO46, .,test-db,AWAITING COMMAND,16,16,11/28 16:30:40,Microsoft SQL Server Management Studio - Query,53 ,0
在搜索这个问题时,我发现人们也遇到过类似的问题,但我无法找出这个问题的根本原因和调试步骤。提供停止 SQL 服务器作为退出这些后台进程的解决方案,但在我们的案例中这是不可行的,因为恢复数据库的代码运行非常频繁,导致这个问题的频率很高。
我还确保 SQL Server 代理没有运行。服务器上运行的 SQL 服务有 SQL Server、SQL Server Browser 和 SQL Server VSS Writer。