sql server - How to get latest file name from folder? -


i have used below list of files folder. list need latest file name.

please suggest, need change code latest file name?

drop table #file go --===== create holding table file names  create table #file         (         filename    sysname,         depth       tinyint,         isfile      tinyint         ) ; --===== capture names in desired directory      -- (change "c:\temp" directory of choice)  insert #file         (filename, depth, isfile)  exec xp_dirtree n'\\backup-server\include\monthly\sales\',1,1  ; --===== find latest file using "constant" characters      -- in file name , iso style date.  select top 1          filename    #file   isfile = 1     , filename 'sales_backup_*.bak' escape '_'   order filename desc    select *from #file 

so in case, file name contains appears creation date number.
sales_backup_201201312300.rar means file created on 2012-01-31 @ 23:00.
have file largest number in it's name:

 select top 1 filename, depth, isfile  #file  isfile = 1  order cast(substring(filename, patindex('%[0-9]%', filename), 12) bigint) desc 

note: if of files not contain numbers in it's name, sql statement raise error. overcome can this:

 ;with cte  (      select filename, depth, isfile      #file      isfile = 1      , patindex('%[0-9]%', filename) > 0  )   select top 1 filename, depth, isfile  cte  order cast(substring(filename, patindex('%[0-9]%', filename), 12) bigint) desc 

update:

following comment, first need unify file names before can compare them. came solution:

;with cte (     select  filename,             depth,              replace(              case when patindex('%[0-9][_][0-9]%', filename) = 0                     replace(filename, '.rar', '00_0000000.rar')             else                  filename             end, '_', '')             unifiedformatfilename     #file     isfile = 1     , patindex('%[0-9]%', filename) > 0 )  select top 1 filename, depth cte order cast(substring(unifiedformatfilename, patindex('%[0-9]%', unifiedformatfilename), 21) numeric(21,0)) desc 

you can see in action on rextester.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -