一般数据库损坏可以尝试使用dbcc checkdb(‘dbname’)直接处理即可,但有时直接使用此方法不会显示任何的错误信息,且不会有任何的修复动作。
然后尝试使用checktable命令则有反应且可以恢复,但数据表多的时候不可能自己手动一个个复制表名执行吧,这时候遍历所有数据表依次修复数据表是不错的解决方案。
首先需要将数据库设置为单用户连接,恢复完毕后取消单用户设置即可。

设置单用户模式:
declare @dbname varchar(255)      
set @dbname='UFDATA_002_2016'      
exec sp_dboption @dbname,'single user','true'    

取消单用户模式:
exec sp_dboption @dbname,'single user','false'    

修复的sql代码如下:
该代码效果是使遍历当前数据库的表,将所有表依次执行checktable操作。

use ufdata_001_2016
go
declare @i int, @val nvarchar(100)
set @i = 4700
while @i <= 5397
begin
	select @val = name from 
	(select ROW_NUMBER() over(order by name) rowid, name from sys.tables) a
	where rowid = @i
	
	if object_id(@val,N'U') is not null	
	begin
	dbcc checktable(@val,REPAIR_ALLOW_DATA_LOSS)      
	dbcc checktable(@val,REPAIR_REBUILD)  
	end
	 set @i = @i + 1
end

另损坏的数据表直接select查询时,有可能会报这个错误:
消息 605,级别 21,状态 3,第 2 行
尝试在数据库 9 中提取逻辑页 (1:18488) 失败。该逻辑页属于分配单元 281474979397632,而非 281474980642816。
以下为查询对应表名的语句,将查询出来的表名手动进行checktable修复以解决问题。

SELECT au.allocation_unit_id, OBJECT_NAME(p.object_id) AS table_name, fg.name AS filegroup_name,
au.type_desc AS allocation_type, au.data_pages, partition_number
FROM sys.allocation_units AS au
JOIN sys.partitions AS p ON au.container_id = p.partition_id
JOIN sys.filegroups AS fg ON fg.data_space_id = au.data_space_id
WHERE au.allocation_unit_id = 281474979397632 OR au.allocation_unit_id = 281474980642816
ORDER BY au.allocation_unit_id;