Solved

Iterate through a collection of files in T-SQL

Posted on 2014-01-04
4
495 Views
Last Modified: 2014-01-04
I want to iterate through all the jpeg files in a folder, inserting them into a filestream column in SQL Server. I have a stored procedure to insert the files, but I don't know how to read through a series of folders and files using T-SQL.
0
Comment
Question by:TimHudspith
  • 2
4 Comments
 
LVL 26

Expert Comment

by:tigin44
ID: 39755855
you can achive this by using xp_cmdshell commands and bulk copy.
0
 

Author Comment

by:TimHudspith
ID: 39755860
Can you give me an example?
0
 
LVL 26

Expert Comment

by:tigin44
ID: 39755897
0
 
LVL 12

Accepted Solution

by:
Habib Pourfard earned 500 total points
ID: 39755911
You can try the following code:

IF OBJECT_ID('tempdb..#Files') IS NOT NULL DROP TABLE #Files;

CREATE TABLE #Files
    (
      ID INT IDENTITY(1, 1) ,
      Subdirectory NVARCHAR(512) ,
      Depth INT ,
      IsFile BIT
    );

INSERT  #Files( Subdirectory, Depth, IsFile )
EXEC master.sys.xp_dirtree 'C:\', 1, 1;

DECLARE @ID INT        
DECLARE FileCursor CURSOR FAST_FORWARD
FOR
    SELECT  ID
    FROM    #Files
    WHERE   IsFile = 1
    ORDER BY ID

OPEN FileCursor
FETCH NEXT FROM FileCursor INTO @ID

WHILE @@FETCH_STATUS = 0 
    BEGIN   
        DECLARE @FileName VARCHAR(256)
        SELECT  @FileName = Subdirectory
        FROM    #Files
        WHERE   ID = @ID

        PRINT @FileName

	FETCH NEXT FROM FileCursor INTO @ID;
    END
CLOSE FileCursor;
DEALLOCATE FileCursor;

Open in new window


instead of print @filename write your own code for each iteration.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how the fundamental information of how to create a table.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

27 Experts available now in Live!

Get 1:1 Help Now