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
Also Read
Copy or Delete files from window directory in SQL Server
SQL Server Import .CSV file in Database
52,765 total views, 9 views today