shrink log和查询数据库 backup,restore,shrink 进度 和 还原历史 的sql (for sqlserver)re

时间:2024-02-23 19:49:09
DBCC SHRINKFILE (N\'DNName_Log\' , 11, TRUNCATEONLY) --shrink log don\'t forget "use dbname"


SELECT DB_NAME(er.[database_id]) [DatabaseName],er.[session_id] AS [SessionID],er.[command] AS [CommandType],est.[text] [StatementText],er.[status] AS [Status],CONVERT(DECIMAL(5, 2), er.[percent_complete]) AS [Complete_Percent],CONVERT(DECIMAL(38, 2), er.[total_elapsed_time] / 60000.00) AS [ElapsedTime_m],CONVERT(DECIMAL(38, 2), er.[estimated_completion_time] / 60000.00) AS [EstimatedCompletionTime_m],er.[last_wait_type] [LastWait],er.[wait_resource] [CurrentWait]FROM sys.dm_exec_requests AS er INNER JOIN sys.dm_exec_sessions AS es ON er.[session_id] = es.[session_id]CROSS APPLY sys.dm_exec_sql_text(er.[sql_handle]) estWHERE er.[command] = \'BACKUP DATABASE\'

cross apply 可以 join 一个表值函数的返回结果,可以参见:http://database.51cto.com/art/201108/283359.htm

sys.dm_exec_sql_text可以根据一个sql session的句柄返回语句

另外如果要获得还原一个数据库的进度,可以把\'BACKUP DATABASE\'改成\'Restore Database\', 附一个简单版本,但是看不到被操作的数据库名字

SELECT 
DB_NAME(er.[database_id]) [DatabaseName],
er.[command] AS [CommandType],
er.[percent_complete],
CONVERT(DECIMAL(5, 2), er.[percent_complete]) AS [Complete_Percent]
,CONVERT(DECIMAL(38, 2), er.[total_elapsed_time] / 60000.00) AS [ElapsedTime_m]
,CONVERT(DECIMAL(38, 2), er.[estimated_completion_time] / 60000.00) AS [EstimatedCompletionTime_m]

FROM sys.dm_exec_requests AS er 

WHERE er.[command] = \'restore DATABASE\'


查询数据库还原的历史:

select * from msdb..restorehistory 
order by restore_date desc


再补充一个查询shrink进度的sql语句:

SELECT 
	percent_complete, 
	start_time, 
	status, 
	command, 
	estimated_completion_time, 
	cpu_time, 
	total_elapsed_time
FROM 
	sys.dm_exec_requests
WHERE
	command = \'DbccFilesCompact\'

2015.7.20:

发现一个很有用的sp, 可以看table的各种属性, 比如是不是有column被当作外键引用

sp_help \'tablename\'

2015.8.25:

recovery就是还原最后一个备份,退出restoring状态.

replace就是覆盖现有数据库