我正在使用c#以编程方式备份某些sql server数据库。我认为Microsoft.SqlServer.Management.Smo和其他一些库是为此目的而制作的。现在我可以备份数据库了。非常好。这是代码:
var server = new Server(@"" + InstanceName);
var backuper = new Backup();
try
{
backuper.Action = BackupActionType.Database;
backuper.Database = DbName;
backuper.Devices.AddDevice(DbName + ".bak", DeviceType.File);
backuper.BackupSetName = DbName + " - Yedek";
backuper.BackupSetDescription = "Açık Bulut Depo - " + DbName + " - Yedek";
backuper.ExpirationDate = DateTime.Now.AddYears(20);
server.ConnectionContext.Connect();
backuper.SqlBackup(server);
}
catch(Exception ex){//..}
我的问题是如何获取数据库备份的设备路径? 我知道我可以指定自己的路径:
backuper.Devices.AddDevice("C:\SOMEPATH\" + DbName + ".bak", DeviceType.File);
然后我实际上可以知道它在哪里,但我想要做的是将其备份到默认位置并获取其路径。请帮帮我。
答案 0 :(得分:4)
在这篇博客文章中,您可以使用以下功能:
http://www.mssqltips.com/sqlservertip/1966/function-to-return-default-sql-server-backup-folder/
CREATE FUNCTION dbo.fn_SQLServerBackupDir()
RETURNS NVARCHAR(4000)
AS
BEGIN
DECLARE @path NVARCHAR(4000)
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',N'BackupDirectory',
@path OUTPUT,
'no_output'
RETURN @path
END;
答案 1 :(得分:4)
正确回答此副本可在此处找到:https://stackoverflow.com/a/8791588/331889
Server.BackupDirectory;
鉴于您已经在使用SMO对象,它应该是最简单的答案。
答案 2 :(得分:0)
我通常在backuper.SqlBackup(server);
之后立即执行以下存储过程
返回最新的备份目标路径。我使用这种方法是因为使用SMO,我给应用程序用户提供了备份到任何位置/驱动器甚至USB磁盘的灵活性。因此,用户可能决定不备份到默认备份位置,并且我希望在备份过程成功完成后返回该位置。
USE [YouDatabaseNameHere]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: SQL.NET Warrior
-- =============================================
CREATE PROCEDURE [dbo].[GetBackupHistory]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQLVer SQL_VARIANT
,@DBName VARCHAR(128)
,@NumDays SMALLINT
,@SQL VARCHAR(1024)
,@WhereClause VARCHAR(256)
SET @DBName = Null
;
SET @NumDays = 14
;
SET @SQLVer = CONVERT(INTEGER, PARSENAME(CONVERT(VARCHAR(20),SERVERPROPERTY('ProductVersion')),4));
SET @WhereClause = 'WHERE a.type IN (''D'',''I'')
And a.backup_start_date > GETDATE()- ' + CAST(@NumDays AS VARCHAR)+''
IF @DBName IS NOT NULL
BEGIN
SET @WhereClause = @WhereClause + '
AND a.database_name = '''+ @DBName +''''
END
SET @SQL = '
SELECT TOP 1 a.database_name,a.backup_start_date
,b.physical_device_name AS BackupPath
,a.position
,a.type
,a.backup_size/1024/1024 AS BackupSizeMB
,' + CASE
WHEN @SQLVer < 10
THEN '0'
ELSE 'a.compressed_backup_size/1024/1024'
END + ' AS CompressedBackMB
FROM msdb.dbo.backupset a
INNER JOIN msdb.dbo.backupmediafamily b
ON a.media_set_id = b.media_set_id
' + @WhereClause + '
ORDER BY a.backup_start_date DESC;';
--PRINT @SQL
EXECUTE (@SQL);
END;
GO