SQL SERVER 数据库备份详细代码

本文实例为大家分享SQL SERVER数据库备份的具体代码,供大家参考,具体内容如下

/**
批量循环备份用户数据库,做为数据库迁移临时用
*/

SET NOCOUNT ON

DECLARE @d varchar(8)
DECLARE @Backup_Flag NVARCHAR(10)

SET @d=convert(varchar(8),getdate(),112)

/***自定义选择备份哪些数据库****/
–SET @Backup_Flag=’UserDB’ — 所用的用户数据库
SET @Backup_Flag=’AlwaysOnDB’ — AlwaysOn 用户数据库

CREATE TABLE #T (ID INT NOT NULL IDENTITY(1,1),SQLBak NVARCHAR(MAX) NOT NULL)

IF @Backup_Flag=’UserDB’
BEGIN

INSERT INTO #T (SQLBak)
SELECT
‘BACKUP DATABASE [‘ + name + ‘] TO DISK=”E:\Backup\’ + NAME + ‘_Full_’+@d+’.bak” WITH CHECKSUM,NOFORMAT,INIT,SKIP,COMPRESSION’ AS ‘SQLBak’
FROM sys.databases
WHERE database_id>4

END

IF @Backup_Flag=’AlwaysOnDB’
BEGIN

INSERT INTO #T (SQLBak)
SELECT
‘BACKUP DATABASE [‘ + database_name + ‘] TO DISK=”E:\Backup\’ + database_name + ‘_Full_’+@d+’.bak” WITH CHECKSUM,NOFORMAT,INIT,SKIP,COMPRESSION’ AS ‘SQLBak’
FROM sys.availability_databases_cluster
END

DECLARE
@Minid INT ,
@Maxid INT ,
@sql VARCHAR(max)
SELECT @Minid = MIN(id) ,
@Maxid = MAX(id)
FROM #T

PRINT N’–打印备份脚本……….’

WHILE @Minid <= @Maxid
BEGIN
SELECT @sql = SQLBak
FROM #T
WHERE id = @Minid
—-exec (@sql)
PRINT ( @sql )
SET @Minid = @Minid + 1
END

DROP TABLE #T

以上所述是小编给大家介绍的SQL SERVER数据库备份详解整合,大家如有疑问可以留言,或者联系站长。感谢亲们支持!!!


数据运维技术 » SQL SERVER 数据库备份详细代码