How to get the list of all the files in a folder in SQL table?
Using SQL Server built-in extended stored procedure called xp_cmdshell you can access the files name from folder to SQL tables, but first you need to enable this in SQL Server, by default it is disabled.
Following are the steps to enabling it, First enable advance option in master database.
USE master; GO -- To allow advanced options to be changed. EXECUTE sp_configure 'show advanced options', 1; GO -- To update the currently configured value for advanced options. RECONFIGURE; GO
Now, Enable Xp_cmdshell extended stored procedure.
-- To enable the feature. EXEC sp_configure 'xp_cmdshell', 1; GO -- To update the currently configured value for this feature. RECONFIGURE;
Now, you can see we have four excel files in folder dir — C:/databasefile, and we want to get all these file name in a SQL table.
There are two ways to get the list of folders files in a SQL table.
1 > Using xp_cmdshell
CREATE TABLE tblgetfileList (excelFileName VARCHAR(100)); INSERT INTO tblgetfileList EXEC xp_cmdshell 'dir /B "D:\databasefile"'; select * from tblgetfileList
2> Using xp_DirTree
exec xp_DirTree directory , depth , file
- directory – This is the directory path of any files .
- depth – It specify the subfolder levels to display. The default of 0 will display all subfolders.
- file – This will either display files as well as each folder. The default of 0 will not display any files.
DECLARE @dirPath nvarchar(500) = 'D:\databasefile' DECLARE @tblgetfileList TABLE (FileName nvarchar(500) ,depth int ,isFile int) INSERT INTO @tblgetfileList EXEC xp_DirTree @dirPath,1,1 SELECT FileName from @tblgetfileList where isFile=1
9,613 total views, 4 views today