我正在使用TSQL脚本,该脚本使用 xp_dirtree 从具有多个bak文件的目录中获取文件名,然后还原到使用所选文件名和目录的数据库。
但是,我希望能够从所述文件夹中选择MOST RECENT文件。目前,脚本仅在按文件名排序后选择顶部。
该文件夹可能如下所示:
------------
File1.BAK
File2.BAK
File3.BAK
File4.BAK
------------
我的脚本目前看起来像这样:
DECLARE @dir varchar(60)
SET @dir = 'C:\TestFolder\'
CREATE TABLE #DirectoryTree (
id int IDENTITY(1,1)
,subdirectory nvarchar(512)
,depth int
,isfile bit);
INSERT #DirectoryTree (subdirectory,depth,isfile)
EXEC master.sys.xp_dirtree @dir,1,1;
DECLARE @file varchar(60) =
(SELECT TOP 1 subdirectory
FROM #DirectoryTree
WHERE isfile = 1 AND RIGHT(subdirectory,4) = '.BAK'
ORDER BY subdirectory DESC)
SET @dir = @dir+@file
PRINT '--Selected file: "'+@dir+'"'
GO
DROP TABLE #DirectoryTree
--restores from file
restore database TESTDB
from disk = @dir
with replace, file = 1
答案 0 :(得分:2)
Dirtree不会返回该信息。 Xp_cmdshell可以,并且必须在您的dba可能允许或不允许的实例上启用它。如果它是一个解决方案:
create table #files (name varchar(500))
insert into #files
EXEC xp_cmdshell 'dir *.exe';
-- find name after list space in string....
select name, REVERSE(SUBSTRING(REVERSE(name),0,CHARINDEX(' ',REVERSE(name))))
from #files
-- dates start with numeric --check assumption carefully...
where isnumeric(left(name,1))=1
--order by date desc --
order by CAST(left(name,17) as datetime) desc