USE [wechat]GO/****** Object: StoredProcedure [dbo].[p_backupdb] Script Date: 2017/11/22 11:38:23 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROC [dbo].[p_backupdb]@dbname sysname='', --要备份的数据库名称,不指定则备份当前数据库@bkpath NVARCHAR(260)='', --备份文件的存放目录,不指定则使用SQL默认的备份目录@bkfname NVARCHAR(260)='', --备份文件名,文件名中可以用\DBNAME\代表数据库名,\DATE\代表日期,\TIME\代表时间@bktype NVARCHAR(10)='DB', --备份类型:'DB'备份数据库,'DF' 差异备份,'LOG' 日志备份@appendfile BIT=1, --追加/覆盖备份文件@password NVARCHAR(20)='' --为备份文件设置的密码(仅sql2000支持),设置后,恢复时必须提供此密码AS DECLARE @sql VARCHAR(8000) IF ISNULL(@dbname,'')='' SET @dbname=DB_NAME() 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 IF ISNULL(@bkfname,'')='' SET @bkfname='\DBNAME\_\DATE\_\TIME\.BAK' SET @bkfname=REPLACE(REPLACE(REPLACE(@bkfname,'\DBNAME\',@dbname) ,'\DATE\',CONVERT(VARCHAR,GETDATE(),112)) ,'\TIME\',REPLACE(CONVERT(VARCHAR,GETDATE(),108),':','')) SET @sql='backup '+CASE @bktype WHEN 'LOG' THEN 'log ' ELSE 'database ' END +@dbname +' to disk='''+@bkpath+@bkfname +''' with '+CASE @bktype WHEN 'DF' THEN 'DIFFERENTIAL,' ELSE '' END +CASE @appendfile WHEN 1 THEN 'NOINIT' ELSE 'INIT' END +CASE ISNULL(@password,'') WHEN '' THEN '' ELSE ',PASSWORD='''+@password+'''' END EXEC(@sql)GO
调用存储过程方式:
--备份当前数据库exec p_backupdb @bkpath='c:\',@bkfname='\DBNAME\_\DATE\_db.bak' --差异备份当前数据库exec p_backupdb @bkpath='c:\',@bkfname='db_\DATE\_df.bak',@bktype='DF' --备份当前数据库日志exec p_backupdb @bkpath='c:\',@bkfname='db_\DATE\_log.bak',@bktype='LOG'