-- =============================================
-- Author : 樞木
-- Create date: 2011-02-15
-- Description: SQL Server 備份資料庫sql指令碼(區域網路)
-- =============================================
CREATE proc [dbo].[usp_sys_BackupDB]
@DBName varchar(50)=null, --需要備份的資料庫
@BackupType varchar(50)='full' --備份類型 full完整備份 diff差異備份
as
begin
exec sp_configure 'show advanced options', 1
reconfigure
declare @DBName varchar(50)
declare @BackupType varchar(50)
set @DBName=DB_Name()
set @BackupType='full'
declare @FilePath varchar(100) --備份儲存路徑
declare @FileName varchar(100) --備份檔案全名
declare @Pwd varchar(50) --使用者名稱
declare @Uid varchar(50) --密碼
set @DBName= isnull(@DBName,DB_Name())
set @FilePath='\\192.168.1.125\f$\DBBAK\FULL'
if @BackupType='diff'
begin
set @FilePath=replace(@FilePath,'FULL','DIFF')
end
set @FileName=@FilePath+'\'
+@DBName
+convert(varchar(100),getdate(),112)
+'_'
+@BackupType
set @Pwd='02'
set @Uid='WL-02\Administrator'
exec master..sp_configure 'xp_cmdshell',1
reconfigure
declare @Authority varchar(100)
set @Authority='net use '+@FilePath+' "'+@Pwd+'" /user:"'+@Uid+'"'
exec master..xp_cmdshell @Authority
-- 全備份
if @BackupType='full'
begin
set @FileName=@FileName
+'_'
+ltrim(str(datepart(wk, getdate())%2))
+'.bak'
backup database @DBName to disk = @FileName with init,retaindays=6
end
-- 差異備份
if @BackupType='diff'
begin
set @FileName=@FileName
+'_'
+ltrim(str(datepart(dw, getdate())-1))
+'.bak'
backup database @DBName to disk = @FileName with init,differential,retaindays=6
end
declare @Del varchar(100)
set @Del='net use '+@FilePath+' /delete'
exec master..xp_cmdshell @Del
exec master..sp_configure 'xp_cmdshell',0
reconfigure
exec sp_configure 'show advanced options', 0
reconfigure
end