STEP1:在数据库服务器的master表中创建存储过程sp_BackupDatabase
代码如下
1 USE [master] 2 GO 3 /****** 对象: StoredProcedure [dbo].[sp_BackupDatabase] 脚本日期: 04/09/2019 09:38:30 ******/ 4 SET ANSI_NULLS ON 5 GO 6 SET QUOTED_IDENTIFIER ON 7 GO 8 -- ============================================= 9 -- Author: RyanDing 10 -- Create date: 2010-10-10 11 -- Description: 备份数据库 12 -- Parameter1: 数据库名 13 -- Parameter2: 备份类型 F=全部, D=差异, L=日志 14 -- ============================================= 15 CREATE PROCEDURE [dbo].[sp_BackupDatabase] 16 @databaseName sysname, @backupType CHAR(1) 17 AS 18 BEGIN 19 SET NOCOUNT ON; 20 21 DECLARE @sqlCommand NVARCHAR(1000) 22 DECLARE @dateTime NVARCHAR(20) 23 24 SELECT @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),111),'/','') + 25 REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','') 26 27 IF @backupType = 'F' 28 SET @sqlCommand = 'BACKUP DATABASE ' + @databaseName + 29 ' TO DISK = ''F:SQLExpressAutoBackup' + @databaseName + '_Full_' + @dateTime + '.BAK''' 30 31 IF @backupType = 'D' 32 SET @sqlCommand = 'BACKUP DATABASE ' + @databaseName + 33 ' TO DISK = ''F:SQLExpressAutoBackup' + @databaseName + '_Diff_' + @dateTime + '.BAK'' WITH DIFFERENTIAL' 34 35 IF @backupType = 'L' 36 SET @sqlCommand = 'BACKUP LOG ' + @databaseName + 37 ' TO DISK = ''F:SQLExpressAutoBackup' + @databaseName + '_Log_' + @dateTime + '.TRN''' 38 39 EXECUTE sp_executesql @sqlCommand 40 END
STEP2:创建SQL文本,代码如下:保存成backup.sql文件即可
1 exec [sp_BackupDatabase] 'WeightCommon','F' 2 go
STEP3:创建批处理文件,以下代码保存成SQLRun.bat即可
@ECHO OFF SET dbhost=MS-20161018OMFZSQLEXPRESS SET dbuser=sa SET dbpasswd=sasa set dbName=master SET sqlpath=%~dp0 set sqlfile=Backup.sql osql -S %dbhost% -U %dbuser% -P %dbpasswd% -d %dbName% -i %sqlpath%%sqlfile% ECHO 完成! PAUSE @ECHO Done!
效果如下: