查询一个目录下(包括子目录)特定类型的文件,并且获得文件的绝对路径

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_split]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_split]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_dirtree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_dirtree]
GO

/*--返回指定目录下的所有目录/文件

调用系统扩展存储过程进行检索

--邹建 2004.09(引用请保留此信息)--*/

/*--调用示例

exec p_dirtree 'c:\winnt',2,2,'%.txt'
--*/

--处理目录分解
create function f_split(@s Nvarchar(2000),@pos int)
returns nvarchar(2000)
as
begin
declare @i int
set @i=charindex('',@s)
while @i>0 and @pos>1
select @i=charindex('',@s,@i+1),@pos=@pos-1
return(case @pos when 1 then case when @i>0 then left(@s,@i) else @s end else '' end)
end
go

--存储过程,实现目录/文件检索
create proc p_dirtree
@path nvarchar(1000), --要查询的目录名
@depth int=1, --要检索的目录层数,如果是0,表示搜索所有的目录
@file int=2, --检索的类型,为0,表示只返回目录,为1,只返回文件,为2,返回文件及目录
@filter nvarchar(10)='' --要返回的目录/文件的匹配条件,规则是like的匹配规则
as
set nocount on
declare @s nvarchar(4000),@i int

--规范参数
if isnull(@path,'')='' return
if right(@path,1)<>'' set @path=@path+''
if isnull(@depth,-1)<0 set @depth=1
if isnull(@file,0) not in(0,1,2) set @file=2
set @i=len(@path)-len(replace(@path,'',''))-1

--检索目录/文件
create table #t(subdirectory nvarchar(2000),depth int,isfile bit default 0)
if @file=0
insert #t(subdirectory,depth) exec master..xp_dirtree @path,@depth,0
else
insert #t exec master..xp_dirtree @path,@depth,1

--补充目录信息
set @depth=0
update #t set @path=case
when isfile=1 then dbo.f_split(@path,depth+@i)
else dbo.f_split(@path,depth+@i)+subdirectory+''
end
,subdirectory=case when isfile=1 then @path+subdirectory else @path end
,@depth=depth

--返回结果
select @s=case when @file=1 then ' and isfile=1' else '' end
+case when @filter='' then '' else ' and subdirectory like @filter' end
,@s='select * from #t'+case when @s='' then '' else ' where '+stuff(@s,1,4,'') end
exec sp_executesql @s,N'@filter nvarchar(10)',@filter
go

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus