上一篇是批量还原数据库,这次写个批量备份数据库。
执行前需要赋值的变量:
@backupFilePath:备份文件夹
@backupFileName:备份文件名后缀,可为空
@DataBackup:要备份的库名
完整SQL语句:
--批量备份
--备份文件夹
DECLARE @backupFilePath NVARCHAR(MAX) = 'E:\MSSQL\AutoBackup\'
DECLARE @backupFileName NVARCHAR(MAX) = '_20240401'
--定义临时表存储要备份的数据库名
DECLARE @DataBackup TABLE (name NVARCHAR(100));
--自定语句:要备份的库名
INSERT INTO @DataBackup
SELECT N'Base1'
UNION SELECT N'Base2'
-----分割线-----
--数据库名
DECLARE @databaseName NVARCHAR(MAX)
--定义游标
DECLARE db_cursor CURSOR FOR
--防止输入错名称
SELECT name FROM master.sys.databases WHERE database_id > 4
and name in (select name from @DataBackup)
--打开游标
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @databaseName
WHILE @@FETCH_STATUS = 0
BEGIN
--备份语句
DECLARE @backupStatement NVARCHAR(MAX)
SET @backupStatement =
'BACKUP DATABASE [' + @databaseName + '] TO DISK = ''' + @backupFilePath + @databaseName + @backupFileName + '.bak'' WITH INIT, NAME = ''' + @databaseName + '-Full Backup'', STATS = 10'
--执行备份语句
print '正在备份'
EXEC (@backupStatement)
--指针
FETCH NEXT FROM db_cursor INTO @databaseName
END
--关闭游标
CLOSE db_cursor
DEALLOCATE db_cursor