我有一个客户端 - 服务器桌面应用程序(.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库)?
答案 0 :(得分: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