利用windows任务计划备份sqlserver
sqlserver Express版不含agent service(虽然可以从“服务”里看到,但是无法启动),因此无法使用代理服务执行备份作业,如果代理作业服务正常,建议还是首先采用代理服务。
此备份方法核心是利用T_SQL 命令和Sqlcmd实用工具
sqlcmd参考:https://docs.microsoft.com/zh-cn/sql/tools/sqlcmd-utility?view=sql-server-2017
Backup命令参考:https://docs.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql?view=sql-server-2017
sqlcmd -a packet_size -A (dedicated administrator connection) -b (terminate batch job if there is an error) -c batch_terminator -C (trust the server certificate) -d db_name -e (echo input) -E (use trusted connection) ....
BACKUP DATABASE MyDatabase
TO backup_destination [ ,...n ]
[ WITH with_options [ ,...o ] ]
范例(使用SQL Server Management Studio执行):
USE MyDatabase; GO BACKUP DATABASE MyDatabase TO DISK = 'C:\SQLServerBackups\MyDatabase.bak' WITH FORMAT, MEDIANAME = 'C_SQLServerBackups', NAME = 'Full Backup of MyDatabase; GO
下面把以上命名包装成存储过程,然后利用sqlcmd命令执行此存储过程(把sqlcmd命令包装到bat文件中,利用windows自带的任务计划执行此bat)
第一步,创建存储过程(使用SQL Server Management Studio执行,注意放到系统数据库master下面)
USE [master] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[sp_BackupDatabases] @databaseName sysname = null, @backupType CHAR(1), @backupLocation nvarchar(200) AS SET NOCOUNT ON; -- DECLARE @BackupName varchar(100) DECLARE @BackupFile varchar(100) DECLARE @sqlCommand NVARCHAR(1000) DECLARE @dateTime NVARCHAR(20)
DECLARE @DBNAME varchar(300)
SET @DBNAME =@databaseName
-- 格式化日期为yyyyhhmmss格式,用作备份文件名称
SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- 存储路径(物理文件名)
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
--逻辑文件名
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
-- 拼接命令
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH NOFORMAT, NOINIT, NAME= ''' +@BackupName+''', SKIP, NOREWIND,NOUNLOAD'
-- 执行备份命令
EXEC(@sqlCommand)
第二步:创建脚本文件sqlbackup.bat(可以把下面的命令复制到CMD控制台执行一下,进行测试,看是否生成了备份文件,能成功执行则复制到sqlbackup.bat文件中,再进行第三步,注意当前windows登陆用户为管理员)
sqlcmd -S yourservername\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='D:\SQLBackups\', @databaseName='[mydatabase]', @backupType='F'"
第三步,添加任务计划
任务计划中,创建基本任务,根据实际情况进行设置触发器,程序或脚本选择sqlbackup.bat的路径,完成设置。
文章链接:https://sqlbackupandftp.com/blog/how-to-automate-sql-server-database-backups#tsql