In SQL Server, we read data from single text file; excel file…etc. However we can extend this to read all the files in a particular directory. This post demonstrates a part of this scenario. Here we will discuss how to get the list of files from a particular directory, then can be extended to load them into SQL Server, which is not the scope of this post.
So in order to use xp_cmdshell, we need to enable it as it is disabled by default.
Here is the way to enable:
1
2
3
4
5
6
7
8
9
10
11
12
| --allow advanced options to be changed.EXEC sp_configure 'show advanced options', 1GO--Update the currently configured value for advanced options.RECONFIGUREGO--Enable XP_CMDSHELLEXEC sp_configure 'xp_cmdshell', 1GO--Update the currently configured value for this feature.RECONFIGUREGO |
Refer Image-1 for the list of files in the directory. Now create a table and load the file list into it:
(Image-1)
1
2
3
4
5
6
7
8
9
10
11
12
13
| --Create the table to store file listCREATE TABLE myFileList (FileNumber INT IDENTITY,FileName VARCHAR(256))--Insert file list from directory to SQL ServerDECLARE @Path varchar(256) = 'dir C:\Import\'DECLARE @Command varchar(1024) = @Path + ' /A-D /B'INSERT INTO myFileListEXEC MASTER.dbo.xp_cmdshell @Command--Check the listSELECT * FROM myFileListGO--Clean upDROP TABLE myFileListGO |