由于机房电源线路故障,导致部分服务器飞正常状态下关机,电源线路重新恢复后,启动服务器后实例下有个数据库都显⽰“恢复挂起”状态,应用程序也⽆法对数据库的正常访问操作。
1、解决关键⽅法:
run DBCC CHECKDB on the database with REPAIR_ALLOW_DATA_LOSS option to repair the db
DBCC CHECKDB (databasename, REPAIR_ALLOW_DATA_LOSS)
GO
2、详细的解决步骤
2.1、设置数据库为紧急模式
ALTER DATABASE [Database-Name] SET EMERGENCY
GO
-- OR
ALTER DATABASE [Database-Name] SET EMERGENCY WITH ROLLBACK IMMEDIATE
GO
-- OR
ALTER DATABASE [Database-Name] SET EMERGENCY WITH ROLLBACK AFTER 60 SECONDS
GO
/*
you may not be able to change the db status to EMERGENCY mode due to several active connections.
You can detect the active connections in SQL Server using the “sp_who2” command.
Once detected, either let the active sessions to complete or terminate them manually by using the “KILL” command
由于多个活动连接,您可能无法将数据库状态更改为 EMERGENCY 模式。
可以使用“sp_who2”命令检测 SQL Server 中的活动连接。检测到后,使用“KILL”命令手动终止活动会话或手动终止活动会话
*/
select * from sys.databases;
select * from sys.sysprocesses where dbid=20;
kill 153
kill 168
# kill 数据库的连接会话
2.2、设置数据库变为单用户模式
-- 使数据库变为单用户模式
ALTER DATABASE [Database-Name] SET SINGLE_USER
GO
-- OR
ALTER DATABASE [Database-Name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
2.3、执行DBCC CHECKDB
DBCC CheckDB ([Database-Name], REPAIR_ALLOW_DATA_LOSS)
GO
/*
DBCC statements can also be used when the database is in an emergency state. We can run DBCC CHECKDB to check for corruption.
In addition, we can use the REPAIR_ALLOW_DATA_LOSS option. When using the REPAIR_ALLOW_DATA_LOSS option, damaged data or indexes may be removed to make the database physically consistent.
As the option indicates, by using this option anomalies of the database will be removed which may cause some data loss.
In addition, if there are problems with transaction log corruption, this command will rebuild the log file.
当数据库处于紧急状态时,也可以使用DBCC语句。我们可以运行DBCC CHECKDB来检查是否损坏。
此外,我们可以使用REPAIR_ALLOW_DATA_LOSS选项。使用REPAIR_ALLOW_DATA_LOSS选项时,可能会删除损坏的数据或索引,以使数据库在物理上保持一致。
如选项所示,使用此选项将删除数据库的异常情况,这可能会导致一些数据丢失。
此外,如果事务日志损坏有问题,此命令将重新生成日志文件。
*/
2.4、设置数据库变回为多⽤户模式
ALTER DATABASE [Database-Name] SET MULTI_USER
GO
-- OR
ALTER DATABASE [Database-Name] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO
2.5、查看错误日志信息
DECLARE @getdateS DATETIME=GETDATE()-30,@getdateE DATETIME=GETDATE()
EXEC xp_readerrorlog 0, --ArchiveID (First error log = 0)
1, --Log type (SQL Server = 1, SQL Agent = 2)
N'', --Filter ProcessInfo
N'', --Filter Text
@getdateS, --DateFrom
@getdateE, --DateTill
'DESC'