SQL Server Stored Procedure to Return Details on Files in Directory

Hi.  I have the following procedure which I found, which seems to work well.   It accepts a single parameter of a file path.  It then inserts records containing details for each file in that path.

The problem I am experiencing is that after the 255th iteration of the While loop it inserts the same file name and details into the result table usr_EJ_FILE_PATHS for all remaining iterations.  

I've stepped through it for a while and I can't seem to see anything wrong with the counter variables.   Thanks in advance if you can see what is wrong with this.  

/****** Object:  StoredProcedure [dbo].[usp_GetDirDetails]    Script Date: 9/19/2015 3:30:20 PM ******/
CREATE PROCEDURE [dbo].[usp_GetDirDetails]
 Replacement code for the sp_GetFileDetails proc that was available in SQL Server 2000 
 which is no longer available in SQL Server 2005 except this gets all the file details 
 for all the files in the directory provided.

 1. If the directory does not exist or there are no files in the directory, an empty
    result set will be returned.
 2. If the trailing backslash on the path is missing, it will be added automatically.
 3. No error checking is done.  Either a valid result set is returned or an empty
    result set is returned (much like a function operates).

 EXEC dbo.GetDirDetails 'drive:path or UNC'

 EXEC dbo.GetDirDetails 'C:\Temp'
 ... or ...
 EXEC dbo.GetDirDetails 'C:\Temp\'

 Revision History:
 Rev 00 - 05/23/2008 - Jeff Moden
                     - Initial concept borrowed from Simple-Talk.com (Phil Factor) and
                       modified for multiple files.
 Rev 01 - 05/25/2008 - Jeff Moden
                     - Formalize the code for use.
--===== Declare the I/O parameters
        @piFullPath VARCHAR(128)

--===== Suppress the auto-display of rowcounts so as not to interfere with the returned
     -- result set

--      Local variables
--===== These are processing control and reporting variables
DECLARE @Counter          INT          --General purpose counter
DECLARE @CurrentName      VARCHAR(256) --Name of file currently being worked
DECLARE @DirTreeCount     INT          --Remembers number of rows for xp_DirTree
DECLARE @IsFile           BIT          --1 if Name is a file, 0 if not

--===== These are object "handle" variables
DECLARE @ObjFile          INT          --File object
DECLARE @ObjFileSystem    INT          --File System Object  

--===== These variable names match the sp_OAGetProperty options
     -- Made names match so they're less confusing
DECLARE @Attributes       INT          --Read only, Hidden, Archived, etc, as a bit map
DECLARE @DateCreated      DATETIME     --Date file was created
DECLARE @DateLastAccessed DATETIME     --Date file was last read (accessed)
DECLARE @DateLastModified DATETIME     --Date file was last written to
DECLARE @Name             VARCHAR(128) --File Name and Extension
DECLARE @Path             VARCHAR(128) --Full path including file name
DECLARE @ShortName        VARCHAR(12)  --8.3 file name
DECLARE @ShortPath        VARCHAR(100) --8.3 full path including file name
DECLARE @Size             INT          --File size in bytes
DECLARE @Type             VARCHAR(100) --Long Windows file type (eg.'Text Document',etc)

--      Create temporary working tables
--===== Create a place to store all file names derived from xp_DirTree
     IF OBJECT_ID('TempDB..#DirTree','U') IS NOT NULL
        DROP TABLE #DirTree

        RowNum INT IDENTITY(1,1),
        Depth  BIT, 
        IsFile BIT

--===== Create a place to store the file details so we can return all the file details
     -- as a single result set

        RowNum           INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
        Name             VARCHAR(128), --File Name and Extension
        Path             VARCHAR(128), --Full path including file name
        ShortName        VARCHAR(120),  --8.3 file name
        ShortPath        VARCHAR(100), --8.3 full path including file name
        DateCreated      DATETIME,     --Date file was created
        DateLastAccessed DATETIME,     --Date file was last read
        DateLastModified DATETIME,     --Date file was last written to
        Attributes       INT,          --Read only, Compressed, Archived
        ArchiveBit       AS CASE WHEN Attributes&  32=32   THEN 1 ELSE 0 END,
        CompressedBit    AS CASE WHEN Attributes&2048=2048 THEN 1 ELSE 0 END,
        ReadOnlyBit      AS CASE WHEN Attributes&   1=1    THEN 1 ELSE 0 END,
        Size             INT,          --File size in bytes
        Type             VARCHAR(100)  --Long Windows file type (eg.'Text Document',etc)

--      Make sure the full path name provided ends with a backslash
 SELECT @piFullPath = @piFullPath+'\'
  WHERE RIGHT(@piFullPath,1)<>'\'

--      Get all the file names for the directory (includes directory names as IsFile = 0)
--===== Get the file names for the desired path
     -- Note that xp_DirTree is available in SQL Server 2000, 2005, and 2008.
 INSERT INTO #DirTree (Name, Depth, IsFile)
   EXEC Master.dbo.xp_DirTree @piFullPath,1,1 -- Current diretory only, list file names

     -- Remember the row count
    SET @DirTreeCount = @@ROWCOUNT

--===== Update the file names with the path for ease of processing later on
 UPDATE #DirTree
    SET Name = @piFullPath + Name

--      Get the properties for each file.  
--===== Create a file system object and remember the "handle"
   EXEC dbo.sp_OACreate 'Scripting.FileSystemObject', @ObjFileSystem OUT

--===== Step through the file names and get the properties for each file.
    SET @Counter = 1
  WHILE @Counter <= @DirTreeCount
        --===== Get the current name and see if it's a file
         SELECT @CurrentName = Name,
                @IsFile = IsFile
           FROM #DirTree 
          WHERE RowNum = @Counter
        --===== If it's a file, get the details for it
             IF @IsFile = 1 AND @CurrentName LIKE '%%'
                --===== Create an object for the path/file and remember the "handle"
                   EXEC dbo.sp_OAMethod @ObjFileSystem,'GetFile', @ObjFile OUT, @CurrentName
                --===== Get the all the required attributes for the file itself
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'Path',             @Path             OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'ShortPath',        @ShortPath        OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'Name',             @Name             OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'ShortName',        @ShortName        OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'DateCreated',      @DateCreated      OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'DateLastAccessed', @DateLastAccessed OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'DateLastModified', @DateLastModified OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'Attributes',       @Attributes       OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'Size',             @Size             OUT
                   EXEC dbo.sp_OAGetProperty @ObjFile, 'Type',             @Type             OUT
                --===== Insert the file details into the return table        
                 INSERT INTO usr_EJ_FILE_PATHS
                        (Path, ShortPath, Name, ShortName, DateCreated, 
                         DateLastAccessed, DateLastModified, Attributes, Size, Type)
                 SELECT @Path,@ShortPath,@Name,@ShortName,@DateCreated, 
        --===== Increment the loop counter to get the next file or quit
         SELECT @Counter = @Counter + 1

--===== House keeping, destroy and drop the file objects to keep memory leaks from happening
   EXEC sp_OADestroy @ObjFileSystem
   EXEC sp_OADestroy @ObjFile

--===== Return the details for all the files as a single result set.


Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marten RuneSQL Expert/Infrastructure ArchitectCommented:
When I try it, it stopped since I had a shortcut in the path, i e a *.lnk file.

Another try gave me 14155 files in a folder (wich is true)

So It works, There is something stoping it. Either permissions on some file, maybe an encryption on some file, or as in my first try, a shortcut in the folder.

Regards Marten
PS I also had to enable 'Ole Automation Procedures' to make the script work.
A third try showed me that it skipped hidden system files, could be nice to know.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AD1080Author Commented:
Thanks for looking at it.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.