我用下面的方法从文件夹中获取文件列表。对于列表,我只需要获取最新的文件名。
请提示,我需要在哪里更改代码才能获取最新的文件名?
DROP TABLE #File
GO
--===== Create a holding table for the file names
CREATE TABLE #File
(
FileName SYSNAME,
Depth TINYINT,
IsFile TINYINT
)
;
--===== Capture the names in the desired directory
-- (Change "C:\Temp" to the directory of your choice)
INSERT INTO #File
(FileName, Depth, IsFile)
EXEC xp_DirTree N'\\Backup-server\Include\Monthly\Sales\',1,1
;
--===== Find the latest file using the "constant" characters
-- in the file name and the ISO style date.
SELECT TOP 1
FileName
FROM #File
WHERE IsFile = 1
AND FileName LIKE 'Sales_backup_*.bak' ESCAPE '_'
ORDER BY FileName DESC
select *from #file
答案 0 :(得分:0)
因此,在这种情况下,文件名包含似乎是创建日期的数字
Sales_backup_201201312300.rar
可能意味着该文件是在2012-01-31 23:00创建的
因此,您所要做的就是获取名称中包含最大数字的文件:
SELECT TOP 1 FileName, Depth, IsFile
FROM #File
WHERE IsFile = 1
ORDER BY CAST(SUBSTRING(FileName, PATINDEX('%[0-9]%', FileName), 12) As BigInt) DESC
注意:如果您的任何文件的名称中不包含数字,则此sql语句将引发错误。为了克服这一点,你可以做这样的事情:
;WITH CTE AS
(
SELECT FileName, Depth, IsFile
FROM #File
WHERE IsFile = 1
AND PATINDEX('%[0-9]%', FileName) > 0
)
SELECT TOP 1 FileName, Depth, IsFile
FROM CTE
ORDER BY CAST(SUBSTRING(FileName, PATINDEX('%[0-9]%', FileName), 12) As BigInt) DESC
根据您的评论,您首先需要统一文件名,然后才能进行比较。 为此,我提出了这个解决方案:
;WITH CTE AS
(
SELECT FileName,
Depth,
REPLACE(
CASE WHEN PATINDEX('%[0-9][_][0-9]%', FileName) = 0 THEN
REPLACE(FileName, '.rar', '00_0000000.rar')
ELSE
FileName
END, '_', '')
As UnifiedFormatFileName
FROM #File
WHERE IsFile = 1
AND PATINDEX('%[0-9]%', FileName) > 0
)
SELECT TOP 1 FileName, Depth
FROM CTE
ORDER BY CAST(SUBSTRING(UnifiedFormatFileName, PATINDEX('%[0-9]%', UnifiedFormatFileName), 21) As Numeric(21,0)) DESC
您可以在rextester.
上看到它的实际效果答案 1 :(得分:0)
.rar扩展程序让我觉得这是一个压缩文件。如果它是压缩的,您需要使用某种脚本语言下载它(可能来自FTP文件夹),并使用相同的脚本解压缩并保存文件(在同一文件夹或其他文件夹中)。你可能想看到这个。
请参阅以下链接了解其他一些背景知识。
SQL code to download a file from an FTP
https://www.virtualobjectives.com.au/sqlserver/ftp_scripts.htm
如果您还有其他问题,请回复。
答案 2 :(得分:0)
--My Text File within This path D:\TXTFILE\
IF OBJECT_ID('tempdb..#ZipTable') IS NOT NULL
DROP TABLE #ZipTable
CREATE TABLE #ZipTable(MDATE VARCHAR(8000))
INSERT #ZipTable
EXEC MASTER.DBO.XP_CMDSHELL 'DIR D:\TXTFILE\'
DECLARE @SYS_USR AS NVARCHAR(1000),@PC_NAME AS NVARCHAR(100)
SET @SYS_USR = SYSTEM_USER
SELECT @PC_NAME=SUBSTRING(SUBSTRING(@SYS_USR,PATINDEX('%\%',@SYS_USR),100),2,LEN(SUBSTRING(@SYS_USR,PATINDEX('%\%',@SYS_USR),100)))
print @PC_NAME
print @SYS_USR
Truncate table FinalZip
Insert into FinalZip
SELECT @PC_NAME as USERNAME,SUBSTRING(MDATE,PATINDEX('%[A-Z]%',MDATE),100) FNAME ,SUBSTRING(MDATE,1,18) AS 'MODIFIEDDATE'
FROM #ZipTable WHERE MDATE LIKE '%.txt%'
select * from FinalZip where modifieddate in (select max(modifieddate) from FinalZip)