How do I list files inside a folder in SQL Server without using the xp_cmdshell
stored procedure?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.
Very easy, just use the SQLCMD-syntax.
Remember to enable SQLCMD-mode in the SSMS, look under Query -> SQLCMD Mode
Try execute:
!!DIR
!!:GO
or maybe:
!!DIR "c:/temp"
!!:GO
Can be done using xp_DirTree, then looping through to generate a full file path if required.
Here is an extract of a script I use to restore databases to a test server automatically. It scans a folder and all subfolders for any backup files, then returns the full path.
If you want you can achieve this using a CLR Function/Assembly.
Here's an example which will allow you to select form your result set like a table.
And your SQL query.
Be aware though, your database needs to have CLR Assembly functionaliy enabled using the following SQL Command.
CLR Assemblies (like
XP_CMDShell
) are disabled by default so if the reason for not using XP Cmd Shell is because you don't have permission, then you may be stuck with this option as well... just FYI.I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...
I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.
NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.
Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.
In SSMS:-
then call it
NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.
and wullah! that should work.
You can use xp_dirtree
It takes three parameters:
Path of a Root Directory, Depth up to which you want to get files and folders and the last one is for showing folders only or both folders and files.
EXAMPLE:
EXEC xp_dirtree 'C:\', 2, 1