删除指定数据库日志,可循环执行,清空Tempdb数据库

ALTER proc [dbo].[SYS_DB_Delete_Log]
(
 @DBName varchar(50)
)
as
-- 删除数据库日志
--Create by HDL 20141217
-- 用于将数据库日志文件删除重新创建
-- SYS_DB_Delete_Log 'ImportDB'
-- update by hdl 20170928 处理删除日志后还原成原来模式
--update by hdl 20191209 修改处理TempDb
begin

/*
use Z3
declare @ExecAll varchar(max)
select @ExecAll=ISNULL(@ExecAll+'','')+'exec SYS_DB_Delete_Log '+ name +'
' from sys.databases where database_id>4 and state_desc='ONLINE'
--print @ExecAll
exec (@ExecAll)


USE [tempdb]
GO
DBCC FREESYSTEMCACHE ('ALL')
GO
DBCC SHRINKFILE (N'tempdev' , 500)
GO

*/

--在SQL2008中清除日志就必须在简单模式下进行,等清除动作完毕再调回到完全模式。

--declare @DBName varchar(50)
--set @DBName='HRP01'

declare @LogName varchar(50)
declare @execsql nvarchar(max),@ParaList nvarchar(500)

set @execsql='
 SELECT @LName= name FROM ['+@DBName+'].sys.database_files where type_desc=''LOG''  
 '
set @ParaList='@LName varchar(50) output'
exec sp_executesql @execsql,@ParaList,@LName=@LogName output

--print @LogName

DECLARE @DefModel VARCHAR(100) --'SIMPLE'
SET @DefModel=(SELECT recovery_model_desc FROM sys.databases WHERE name =@DBName)
set @execsql='
 SELECT * FROM ['+@DBName+'].sys.database_files 

USE [master]
ALTER DATABASE ['+@DBName+'] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE ['+@DBName+'] SET RECOVERY SIMPLE --简单模式
USE ['+@DBName+']
DBCC SHRINKFILE (N'''+@LogName+''' , 11, TRUNCATEONLY) 
 --这里的DNName_Log 如果不知道在sys.database_files里是什么名字的话,可以用以下注释的语句进行查询
USE [master] 
ALTER DATABASE ['+@DBName+'] SET RECOVERY '+@DefModel+' WITH NO_WAIT
ALTER DATABASE ['+@DBName+'] SET RECOVERY '+@DefModel+' --还原为完全模式
 
'
SET @execsql=@execsql+ 'SELECT * FROM ['+@DBName+'].sys.database_files '


--print (@execsql)
exec (@execsql)

end
GO
posted @ 2019-12-09 11:26  梦想(胡大利)  阅读(591)  评论(0编辑  收藏  举报