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/

posted on 2006-03-18 23:22  gucs  阅读(2860)  评论(2编辑  收藏  举报

导航