t-sql判断文件夹是否存在

另一个项目的客户发来邮件,希望在SQL Server的存储过程中判断一个文件夹是否存在,如果不存在错误日志;一个在Oracle中很简单的功能,在SQL Server 2000中却……

google了半天,知道可以使用扩展存储过程,也就是以xp_为前缀的,比如xp_cmdshell就是一个扩展的存储过程;

首先测试了xp_subdirs,当文件夹不存在是,不能使用@@error捕捉错误;接着测试了xp_dirtree,又是同样的问题;最后测试xp_fileexist,可这个是判断文件是否存在的,郁闷;

没办法了,于是自己写了一段代码,可以实现判断的功能,就是有点儿麻烦;

 1 create procedure p_dir_exist
 2 
 3 @dirName nvarchar(400),
 4 @dirExist char output
 5 
 6 as
 7 
 8 create table #tt
 9 (
10     col nvarchar(255)
11 )
12 
13 declare @sql nvarchar(4000)
14 declare @cnt int
15  
16 select @sql = 'cd ' + @dirName
17 print @sql
18 
19 insert into #tt
20 exec master..xp_cmdshell @sql
21 
22 delete from #tt
23 where col is null
24 
25 select @cnt = count(1from #tt
26 
27 select @dirExist = '0'
28 if @cnt > 0
29     select @dirExist = '1'
30 
31 drop table #tt

这样调用:

1  declare   @ex   char
2 
3  exec  master.dbo.p_dir_exist  ' X:\TantoHenkoErrorLog ' @ex  output
4 
5  select   @ex

功能实现了,还是有点 不死心,于是继续google,功夫不负有心人,终于找到了;

先是在一个老外的文字中提到:xp_fileexist: Checks to see if a given file exists or not. It returns three columns with a value of 1 (yes) or 0 (no): File Exists, File is a Directory and Parent Directory Exists.

知道使用xp_fileexist可以实现之后,继续google在一个bbs中找到了具体实现:

1  CREATE   TABLE  #tmp ( [ File Exists ]   BIT [ File is a Directory ]   BIT [ Parent Directory Exists ]   BIT )
2 
3  INSERT   INTO  #tmp ( [ File Exists ] [ File is a Directory ] [ Parent Directory Exists ] )
4 
5  EXEC  master.dbo.xp_fileexist  ' c:\WINDOWS '
6 
7  SELECT   *   FROM  #tmp
8 
9  DROP   TABLE  #tmp

另一个跟帖的老外提出了另一种方案(仔细一看,和我实现的道理相似,呵呵,高兴ing): You could also just use xp_cmdshell 'dir blah/blah/blah.blah' and insert into the temp table like Tim is doing. You then just test the results of the temp table. Then if they drop or change these functions, your stuff still works.

下面是搜索过程中找到的几个链接:

http://www.transactsql.com/

http://www.sql-server-performance.com/

转载于:https://www.cnblogs.com/gucsnet/archive/2006/03/18/353120.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值