How can I use T-SQL to find a file name in a windows directory?

In an SQL stored procedure, I need to query a folder in the windows file system and determine whether a specific file name exists in that folder.  Can I do that using T-SQL?
T HoecherlDeveloperAsked:
Who is Participating?
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.

You'll need to use xp_cmdshell which is disabled by default. I'm assuming there are security risks with that, so make sure you understand them before implementing it.

Check out for how to enable xp_cmdshell and use the windows file system.

You'll enable it by using

--allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
--Update the currently configured value for advanced options.
EXEC sp_configure 'xp_cmdshell', 1
--Update the currently configured value for this feature.

Open in new window

Below is code that will get the list of files in the directory.
--Create the table to store file list
CREATE TABLE myFileList (FileNumber INT IDENTITY,FileName VARCHAR(256))
--Insert file list from directory to SQL Server
DECLARE @Path varchar(256) = 'dir C:\Import\'
DECLARE @Command varchar(1024) =  @Path + ' /A-D  /B'
EXEC MASTER.dbo.xp_cmdshell @Command
--Check the list
SELECT * FROM myFileList
--Clean up

Open in new window

That code is from the above URL. You could change the select * from myFileList query to be the file name.

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
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

From novice to tech pro — start learning today.