1

我有一个客户端 - 服务器桌面应用程序 (.NET),客户端必须获取存储在默认备份文件夹 ( C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup)中的可用备份文件列表

我决定创建一个存储过程,它将返回包含所有需要文件的表:

CREATE PROCEDURE [dbo].[spGetBackUpFiles] AS 
SET NOCOUNT ON
BEGIN

declare @backUpPath as table 
(
 name nvarchar(max),
 backuppath nvarchar(max)
)

insert into @backUpPath
EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',    N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory'

declare @table as table 
(
 filename nvarchar(max),
 depth int,
 filefile int
)

declare @backUpFilesPath as nvarchar(max) = (select top 1 backuppath from @backUpPath)

insert into @table
 EXEC xp_dirtree @backUpFilesPath, 1, 1

SELECT * FROM @table WHERE filename like N'MASK[_]%'
END

但我收到以下错误:

消息 0,级别 11,状态 0,行 0
当前命令发生严重错误。结果,如果有的话,应该丢弃。

你可以在你的机器上试试这个脚本......

可能是什么问题?

是否有另一种方法来获取可用备份列表(可能使用 SMO 库)?

4

1 回答 1

2

这与您将文件路径传递给 xp_dirtree 的方式有关,我可以让它工作的唯一方法是使用临时表和动态 SQL,如下所示:

CREATE PROCEDURE [dbo].[spGetBackUpFiles]
AS 
    SET NOCOUNT ON
    BEGIN

        IF OBJECT_ID('tempdb..#table') IS NOT NULL 
            DROP TABLE #table

        CREATE TABLE #table
            (
              [filename] NVARCHAR(MAX) ,
              depth INT ,
              filefile INT
            )

        DECLARE @backUpPath AS TABLE
            (
              name NVARCHAR(MAX) ,
              backuppath VARCHAR(256)
            )

        DECLARE @SQL NVARCHAR(MAX)

        INSERT  INTO @backUpPath
                EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
                    N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer',
                    N'BackupDirectory'

        DECLARE @backUpFilesPath AS NVARCHAR(MAX) = ( SELECT TOP 1
                                                              backuppath
                                                      FROM    @backUpPath
                                                    )



        SET @SQL = 'insert into #table
        EXEC xp_dirtree ''' + @backUpFilesPath + ''', 1, 1'

        EXEC(@SQL)

        SELECT  *
        FROM    #table WHERE [filename] like N'MASK[_]%'
        DROP TABLE #table
    END
于 2013-07-03T13:13:02.027 回答