Thursday, July 3, 2008

Automatic Scheduled database Backup

Necessicity is the mother of invention.......thought i am not inventor,
some time back i was requested to give some utility to the clients that they will schedule the backup database and in certains Drive i.e in C:\Dump folder all of my backup should go....

It is done by creating simple procedure which is shown below:
But before doing so, one must register their devices , by just executing following command
1. EXEC sp_addumpdevice 'disk','mydiskdump','C:\Dump'
after doing this, one will run the procedure and put it in scheduler, your dump will go to C:\drive
USE [master]
GO
/****** Object: StoredProcedure [dbo].[custom_proc_backupdatabase] Script Date: 07/04/2008 10:04:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[custom_proc_backupdatabase] as
-- THIS PROCEDURE IS FOR MAINTANANCE PURPOSE FOR DATABASE
--CREATED BY PARTH ON 5TH MAY 2008
declare
@db varchar(300),
@dbname varchar(300),
@sql nvarchar(1000),
@backupdate varchar(50)
declare c1 cursor for
select name from master..sysdatabases where name not in ('master','tempdb','model','msdb','SharePoint_AdminContent_2edfaf57-7f7a-43d9-9171-e63b1d726f91')
order by name
select @backupdate={fn curdate()}
--Before running this procedure please register your type of backup here e.g DISK,TAPE,NETWORKDISK
-- for that you just have to run following command here :
-- USE master
-- EXEC sp_addumpdevice 'disk','mydiskdump','C:\Dump'
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 @dbname=name from '+@db+'.dbo.sysfiles where fileid=1'
execute sp_executesql @sql,N'@dbname varchar(300) OUT,@db varchar(300)',@dbname OUT,@db
select * from master.dbo.sysfiles
--######################################################################################################
--NOW BY FOLLOWING CODE WE ARE EXECUTING DATABASE COMMAND DYNAMICALLY
-- BY JUST PROVIDING DB NAME
-- Following command will truncate the Log file as well
set @sql='USE '+@db+';'
set @sql=@sql+'BACKUP DATABASE '+@db+''
set @sql=@sql+' TO DISK=''C:\DUMP\'+@db+'_'+@backupdate+''' WITH FORMAT ;'
PRINT @sql
--######################################################################################################
execute sp_executesql @sql,N'@dbname varchar(300)',@dbname
fetch c1 into @db
end
end
close c1
deallocate c1

now.................lol
you are done doing............Cheers

Parth

PS: I am new to SQL, please send me your feedback for better of improvement of this procedures

No comments: