备份SQL Server数据库
网站搬迁之后,备份数据库的功能出错了,原因是原来数据库与网站同一台服务器,现在是数据库与网站分别在不同服务器,引起在备分时,找不到路径或是没有权限存储。
最初版本的存储过程:
代码
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Backup_DataBase]
(
@BackupDataBaseName varchar(128),
@FileName nvarchar(1000)
)
AS
BACKUP DATABASE @BackupDataBaseName TO DISK = @FileName
IF @@ERROR <>0
BEGIN
RAISERROR(N'数据库备份失败!',16,1)
RETURN
END
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Backup_DataBase]
(
@BackupDataBaseName varchar(128),
@FileName nvarchar(1000)
)
AS
BACKUP DATABASE @BackupDataBaseName TO DISK = @FileName
IF @@ERROR <>0
BEGIN
RAISERROR(N'数据库备份失败!',16,1)
RETURN
END
更新后的存储过程:
代码
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Backup_DataBase]
(
@BackupDataBaseName varchar(128),
@FileName nvarchar(128)
)
AS
DECLARE @BKFULLPATH NVARCHAR(1000)
--get SQL server Default Backup path
--reference:http://www.cnblogs.com/insus/articles/1914932.html
SELECT @BKFULLPATH = [dbo].[udf_SQLServerBackupDirectory]() + '\' + @FileName
BACKUP DATABASE @BackupDataBaseName TO DISK = @BKFULLPATH WITH INIT
DECLARE @MapString NVARCHAR(1000)
/*--说明:
L: 是映射网络路径对应本机的盘符,与下面的备份对应
\\192.168.0.37\E$ 是要映射的网络路径
192.168.0.37\administrator
192.168.0.37是远程的计算机名,administrator是登陆的用户名
password:上面指定的administrator用户的密码
--*/
SET @MapString = 'NET USE L: "\\192.168.0.37\E$" "password" "/USER:192.168.0.37\administrator"'
EXECUTE master..xp_cmdshell @MapString
--把备份文件拷贝至映射路径中
DECLARE @CopyString NVARCHAR(1000) = 'COPY "' + @BKFULLPATH + '" L:'
EXECUTE master..xp_cmdshell @CopyString
--删除备份文件
DECLARE @OrgBkFileString NVARCHAR(1000) = 'DEL "' + @BKFULLPATH + '"'
EXECUTE master..xp_cmdshell @OrgBkFileString
--删除映射路径
EXECUTE master..xp_cmdshell 'NET USE L: /DELETE'
IF @@ERROR <> 0
BEGIN
RAISERROR(N'数据库备份失败!',16,1)
RETURN
END
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Backup_DataBase]
(
@BackupDataBaseName varchar(128),
@FileName nvarchar(128)
)
AS
DECLARE @BKFULLPATH NVARCHAR(1000)
--get SQL server Default Backup path
--reference:http://www.cnblogs.com/insus/articles/1914932.html
SELECT @BKFULLPATH = [dbo].[udf_SQLServerBackupDirectory]() + '\' + @FileName
BACKUP DATABASE @BackupDataBaseName TO DISK = @BKFULLPATH WITH INIT
DECLARE @MapString NVARCHAR(1000)
/*--说明:
L: 是映射网络路径对应本机的盘符,与下面的备份对应
\\192.168.0.37\E$ 是要映射的网络路径
192.168.0.37\administrator
192.168.0.37是远程的计算机名,administrator是登陆的用户名
password:上面指定的administrator用户的密码
--*/
SET @MapString = 'NET USE L: "\\192.168.0.37\E$" "password" "/USER:192.168.0.37\administrator"'
EXECUTE master..xp_cmdshell @MapString
--把备份文件拷贝至映射路径中
DECLARE @CopyString NVARCHAR(1000) = 'COPY "' + @BKFULLPATH + '" L:'
EXECUTE master..xp_cmdshell @CopyString
--删除备份文件
DECLARE @OrgBkFileString NVARCHAR(1000) = 'DEL "' + @BKFULLPATH + '"'
EXECUTE master..xp_cmdshell @OrgBkFileString
--删除映射路径
EXECUTE master..xp_cmdshell 'NET USE L: /DELETE'
IF @@ERROR <> 0
BEGIN
RAISERROR(N'数据库备份失败!',16,1)
RETURN
END