The code from above to import multiple images

From MyWiki
Jump to: navigation, search
-- I'm going to assume you already have a destination table like this one set up.
CREATE TABLE Images (fname nvarchar(MAX), DATA varbinary(MAX));
GO
 
-- Set the directory whose images you want to load. The rest of this code assumes that @directory
-- has a terminating backslash.
DECLARE @directory nvarchar(MAX) = N'D:\Images\';
 
-- Query the names of all .JPG files in the given directory. The dir command's /b switch omits ALL
-- data from the output save for the filenames. Note that directories can contain single-quotes, so
-- we need the REPLACE to avoid terminating the string literal too early.
DECLARE @filenames TABLE (fname VARCHAR(MAX));
DECLARE @shellCommand nvarchar(MAX) = N'exec xp_cmdshell ''dir ' + REPLACE(@directory, '''', '''''') + '*.jpg /b''';
INSERT @filenames EXEC(@shellCommand);
 
-- Construct and execute a batch of SQL statements to load the filenames and the contents of the
-- corresponding files into the Images table. I found when I called dir /b via xp_cmdshell above, I
-- always got a null back in the final row, which is why I check for fname IS NOT NULL here.
DECLARE @SQL nvarchar(MAX) = '';
WITH EscapedNameCTE AS (SELECT fname = REPLACE(@directory + fname, '''', '''''') FROM @filenames WHERE fname IS NOT NULL)
SELECT
    @SQL = @SQL + N'insert Images (fname, data) values (''' + E.fname + ''', (select X.* from openrowset(bulk ''' + E.fname + N''', single_blob) X)); '
FROM
    EscapedNameCTE E;
EXEC(@SQL);