Thursday, July 3, 2008

Truncating logfile Dynamically using SP

Hi,
some days back, it happens to 1 of my clients datacenter that suddenly they were unable to insert the data in the database, we tried so many thing like checking for database connectivity, or any other process is going on....etc etc...

suddenly we found out that there is tremendous amout of data is there in LOG file so, for temporary purpose we have take a back ( of course we first stop the process and instances.....as it is recommended) then we create a new Log file for that database

Now the problem was the data flow was so much that we have to do something that will automatically delete the log file so we try building a procedure which will run as per the schedule and deletes the log file and getting back to it's normal size.......

Below is the code for that:

USE [master]
GO
/****** Object: StoredProcedure [dbo].[proc_trunclogfiles] Script Date: 03/09/2008 13:55:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[proc_trunclogfiles] as
-- THIS PROCEDURE IS FOR MAINTANANCE PURPOSE FOR TRUNCATIONG LOG FILES
--CREATED BY PARTH ON 3RD MARCH 2008
declare
@db varchar(300),
@logname varchar(300),
@sql nvarchar(1000)
declare c1 cursor for
select name from master..sysdatabases where name not in ('master','tempdb','model','msdb')
order by name
begin
open c1
fetch c1 into @db
while (@@fetch_status=0)
begin
-- FOLLOWING IS THE USE OF DYNAMIC SQL WHERE WE ARE GETTING DATABASE_NAME AND LOGFILE NAME
set @sql='select @logname=name from '+@db+'.dbo.sysfiles where fileid=2'
execute sp_executesql @sql,N'@logname varchar(300) OUT,@db varchar(300)',@logname OUT,@db
--######################################################################################################
--NOW BY FOLLOWING CODE WE ARE EXECUTING THE TRUNCATE LOG COMMAND DYNAMICALLY
-- BY JUST PROVIDING DB NAME AND LOGNAME
-- Following command will truncate the Log file as well
--set @sql='USE '+@db+';'
--set @sql=@sql+'BACKUP LOG '+@db+' with truncate_only ;'
--set @sql=@sql+' DBCC SHRINKFILE('+@logname+');'
--######################################################################################################
-- FOLLOWING IS THE ANOTHER METHOD TO DO IT...!
set @sql='USE '+@db+';'
set @sql=@sql+' DUMP TRANSACTION '+@db+' WITH NO_LOG;'

execute sp_executesql @sql,N'@logname varchar(300)',@logname
fetch c1 into @db
end
end
close c1
deallocate c1

Hope this will help some one.

Thanks
Parth
PS: as i am new to SQL, please let me know if there is any problem with code or i have done something wrong

No comments: