我想我只是嘗試了xp_cmdshell
爲基礎的辦法踢。我想出了一些看起來對我有用的東西,所以我很想知道當您嘗試使用xp_cmdshell
時遇到了什麼問題。請參閱評論以獲取此處發生的情況的解釋。
-- 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);
我以空表Images
開始。下面是我在運行上面後出現:
現在,我不是說這一定是去這樣做的最佳方式;由@nscheaffer提供的鏈接可能更合適,我會自己閱讀它,因爲我不熟悉SSIS。但也許這將有助於說明你最初嘗試的方式。
可能還有其他的方法可以做到這一點,但我認爲SSIS包會適合你。檢查了這一點... http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/ssis-import-images-table/ – nscheaffer
感謝您編輯文本@marc_s –