一次性備份SQL Server中所有的數(shù)據(jù)
來源:程序員人生 發(fā)布時間:2013-11-13 23:22:46 閱讀次數(shù):3018次
本文原始來自網(wǎng)上一篇文章,不過原始的存儲過程有些問題,本文經(jīng)過驗證并進(jìn)行了進(jìn)一步的修正,增加了備份的時候自動增加備份日期,文章內(nèi)容如下:
備份處理的存儲過程
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/*--備份所有數(shù)據(jù)庫
備份的文件名為數(shù)據(jù)庫名+日期+.bak
將所有的用戶數(shù)據(jù)庫(或指定的數(shù)據(jù)庫列表)
備分到指定的目錄下.
/*--調(diào)用示例
--備份所有用戶數(shù)據(jù)庫
exec p_backupdb @bkpath='D:',@dbname=''
--備份指定數(shù)據(jù)庫
exec p_backupdb @bkpath=D:',@dbname='數(shù)據(jù)庫名稱'
--*/
create proc [dbo].[p_backupdb]
@bkpath nvarchar(260)='D:', --備份文件的存放目錄,不指定則使用SQL默認(rèn)的備份目錄
@dbname nvarchar(4000)='' --要備份的數(shù)據(jù)庫名稱列表,不指定則備份所有用戶數(shù)據(jù)庫
as
declare @sql varchar(8000)
DECLARE @strdate NVARCHAR(200)
set @strdate = convert(NVARCHAR(10),getdate(),120)
set @strdate = REPLACE(@strdate, '-' , '')
--檢查參數(shù)
if isnull(@bkpath,'')=''
begin
select @bkpath=rtrim(reverse(filename)) from master..sysfiles where name='master'
select @bkpath=substring(@bkpath,charindex('',@bkpath)+1,4000)
,@bkpath=reverse(substring(@bkpath,charindex('',@bkpath),4000))+'BACKUP'
end
else if right(@bkpath,1)<>'' set @bkpath=@bkpath+''
--得到要備份的數(shù)據(jù)庫列表
if isnull(@dbname,'')=''
declare tb cursor local for
select name from master..sysdatabases where name not in('master','tempdb','model','msdb')
else
declare tb cursor local for
select name from master..sysdatabases
where name not in('master','tempdb','model','msdb') and(name like '%'+@dbname+'%')
--備份處理
open tb
fetch next from tb into @dbname
while @@fetch_status=0
begin
set @sql='backup database '+@dbname
+' to disk='''+@bkpath+@dbname +'_'+@strdate
+'.bak'' with format'
exec(@sql)
fetch next from tb into @dbname
end
close tb
deallocate tb
go
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈