9

Is it possible to query a folder in TSQL, from SQL Management Studio, and return a list of file names? If so, how?

3 Answers 3

15

You can use xp_cmdshell.

Example:

EXECUTE master.dbo.xp_cmdshell 'DIR "C:\YourDirectory\" /A-D /B'

There's a good, full example with more options here.

Sign up to request clarification or add additional context in comments.

2 Comments

I would disagree. This is like you using command line to bring information but not querying NTFS. And you cannot use any WHERE clause to say select only latest files (Modified Date filter). Good attempt though...
@Faiz The above query does exactly what OP asked though.
7

CLR integration is also an option, if you're not comfortable with allowing xp_cmdshell to be executed.

See MSDN.

1 Comment

+1 because I personally like the features offered by this mechanism - they have come in very useful to me for all kinds of tasks that are obtuse in TSQL. And +10 to Microsoft for creating this .NET integration feature in SQL Server.
5

Years later now there is a DMF called dm_os_enumerate_filesystem that can do this. This was added with SQL 2017.

select * from sys.dm_os_enumerate_filesystem('c:\','*.*')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.