我想我只是尝试了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 –