我编写了以下存储过程来列出给定路径中的文件:
ALTER procedure [dbo].[usp__ListFiles_xml] (
@path varchar(8000),
@xmldata xml output
)
as
begin
DECLARE @ProcName varchar(255) = OBJECT_NAME(@@PROCID);
declare @DirLines table (
RowNum int identity(1,1) not null,
line varchar(8000)
);
declare @DirCommand varchar(8000) = 'dir /A:-D /n "'+@path+'"';
insert into @DirLines
exec xp_cmdshell @DirCOmmand;
declare @DirName varchar(8000) = (select SUBSTRING(line, 15, 8000) from @DirLines where RowNum = 4);
delete from @DirLines
where line is null or isnumeric(LEFT(line, 2)) = 0;
set @xmldata = (
select substring(line, 40, 255) as FileName,
cast(replace(substring(line, 21, 18), ',', '') as bigint) as FileSize,
cast(left(line, 20) as DateTime) as CreationDateTime,
@DirName as DirName
from @DirLines
for xml raw('Dir'), type
)
return;
end; -- usp__ListFiles_xml
您可以将结果选择到表中,找到所需的文件,然后通过执行以下操作从那里继续加载:
declare @xmldata xml;
exec usp__ListFiles_xml @FileTemplate, @xmldata output;
declare @Files table (
FileName varchar(255),
FileSize bigint,
CreationDateTime DateTime,
DirName varchar(8000)
);
insert into @Files
select T.c.value('@FileName', 'varchar(255)') as FileName,
T.c.value('@FileSize', 'bigint') as FileSize,
T.c.value('@CreationDateTime', 'datetime') as CreationDateTime,
T.c.value('@DirName', 'varchar(8000)') as DirName
from @xmldata.nodes('Dir') as T(c);