declare @strsql varchar(1000), --執行語句
@strdirname varchar(50),--建立檔案夾名
@strcmd varchar(50), --執行命令名
@strsend varchar(1000), --郵件發送語句
@strdate varchar(50) --郵件發送日期
set @strsql='backup database pubs to disk=''d:\backup\erp\'
set @strdirname=replace(substring(convert(varchar(20),getdate(),120),1,10),'-','')
set @strcmd='md d:\backup\erp\'
set @strcmd=@strcmd+@strdirname
--取得當天日期,格式為yyyy-mm-dd
set @strdate=substring(convert(varchar(50),getdate(),120),1,10)
set @strsend='sys_sendmail ''1000@hm.com'',''213@hm.com'',''www'',''備份通知'','''+@strdate+'日Database Backup成功,感謝您的使用!'''
exec xp_cmdshell @strcmd
set @strsql=@strsql+@strdirname+'\pubs.dat''with init,nounload,noskip,noformat'
print @strsql
exec (@strsql)
backup database pubs to disk='d:\backup\erp\pubs.dat' with init,nounload,noskip,noformat
--用FTP上傳到ERP伺服器
exec xp_cmdshell 'ftp -s:"D:\backup\erp\ftp.txt"'
--操作成功後發送郵件
exec(@strsend)
if @@error <> 0
begin
raiserror('Database Backup發生錯誤,請檢查設定',16,1)
set @strsend='sys_sendmail ''1000@hm.com'',''213@hm.com'',''www'',''備份通知'','''+@strdate+'日Database Backup失敗,請檢查設定!'''
exec (@strsend)
end
-----------------------------------------------------------------------------------------------------------
下面還有個使用C#來實現備份的
///<summary>
///備份資料庫到本地磁碟
///</summary>
public bool BackUp(string BackUpFile)
{
try
{
//第一步:在伺服器上建立臨時檔案夾
ExecuteSql(@"master..xp_cmdshell 'md C:\temp'");
ExecuteSql(@"master..xp_cmdshell 'del C:\temp\*.* /q'");
//第二步:備份資料庫到伺服器目錄
ExecuteSql(@"backup database " + DataBaseName() + @" to disk='C:\temp\HSSY'");
//第三步:共用伺服器的備份目錄
ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK=C:\temp'");
//第四步:複製伺服器上的備份檔案到本地
File.Copy(@"\\" + ServerIP() + @"\SQLDATABACK\HSSY", BackUpFile,true);
return true;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
//第五步:取消伺服器共用目錄的共用
ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK /delete'");
}
}
/// <summary>
/// 從本地磁碟恢複資料庫
/// </summary>
public bool Restore(string RestoreFile)
{
try
{
//第零步:關閉使用者進程,防止其它使用者正在使用資料庫,導致資料恢複失敗
KillServerUser();
//第一步:在伺服器上建立臨時檔案夾
ExecuteSql(@"master..xp_cmdshell 'md C:\temp'");
ExecuteSql(@"master..xp_cmdshell 'del C:\temp\*.* /q'");
//第二步:共用伺服器的恢複目錄
ExecuteSql(@"master..xp_cmdshell 'net share SQLRESTORE=C:\temp'");
//第三步:複製伺服器上的備份檔案到本地
File.Copy(RestoreFile, @"\\" + ServerIP() + @"\SQLRESTORE\HSSY",true);
//第四步:取消伺服器共用目錄的共用
ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK /delete'");
//第五步:恢複資料庫到伺服器目錄
ExecuteSql(@"restore database " + DataBaseName()+ @" from disk='C:\temp\HSSY'");
return true;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
//第六步:取消伺服器共用目錄的共用
//DbHelperSQL.ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK /delete'");
}
}