sql中查找目录中的文件名

查询一个目录下(包括子目录)特定类型的文件,并且获得文件的绝对路径
主要解答者:zjcxc提交人:zjcxc
感谢:pbsql、zjcxc
审核者:zjcxc社区对应贴子:查看
     A :

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  
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值