Created
November 9, 2013 19:01
-
-
Save derjabkin/7388609 to your computer and use it in GitHub Desktop.
Daily database and hourly log backup on Microsoft SQL Sever
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if not OBJECT_ID('dbo.Proc_BackupDatabaseDailyWithLog') is null | |
Drop Proc dbo.Proc_BackupDatabaseDailyWithLog | |
go | |
Create Proc dbo.Proc_BackupDatabaseDailyWithLog( | |
@DbName sysname, | |
@TargetPath nvarchar(1000)) as | |
Declare @FileName nvarchar(1000) | |
Declare @DirPath nvarchar(1000) | |
Declare @Sql nvarchar(2000) | |
Declare @Exists int | |
Select @DirPath = @TargetPath + '\' + @DbName + '\' + | |
cast(datepart(yyyy,getdate()) as nvarchar(10)) + | |
(Right('00' + cast(DATEPART(mm, getdate()) as nvarchar(20)),2)) + | |
(Right('00' + cast(DATEPART(dd, getdate()) as nvarchar(20)),2)) | |
Select @FileName = @DirPath + '\' + @DbName + '.bak' | |
exec xp_create_subdir @DirPath | |
exec xp_fileexist @FileName, @Exists OUT | |
if (@Exists = 0) | |
Select @Sql = 'backup database ' + QUOTENAME(@DbName) + ' to disk=''' + @FileName + '''' | |
else | |
begin | |
Select @FileName = @DirPath + '\' + @DbName + 'log_' + | |
right('00' + cast(datepart(HOUR,getdate()) as nvarchar(10)),2) + | |
right('00' + cast(DATEPART(MINUTE, getdate()) as nvarchar(20)),2) + | |
right('00' + cast(DATEPART(SECOND, getdate()) as nvarchar(20)),2) + | |
'.bak' | |
Select @Sql = 'backup log' + QUOTENAME(@DbName) + ' to disk=''' + @FileName + '''' | |
end | |
EXEC sp_executesql @Sql | |
go | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment