本文转自:http://blog.csdn.net/shenzhennba/article/details/9305653
在DB 操作时有时需要利用SQL语句检测某路径是否存在,不存在则创建之,这里涉及到几个方面,分别说明如下
检测原理主要是利用系统的xp_cmdshell存储过程执行DOS命令,过程中的信息可以保存在一个临时表中,查询该表即可知道DOS命令的执行结果,从而判断该路径是否存在,进而执行相关的操作,这里xp_cmdshell涉及到安全问题,首先需要dbo权限开启,具体操作如下,以下以SQL Server 2008为例:
-
1 use master 2 go 3 4 --//1,涉及安全问题,(用DBO权限用户)开启使用xp_cmdshell存储过程的权限 5 --SQL Server blocked access to procedure 'xp_cmdshell' 6 sp_configure 'show advanced options', 1 7 go 8 reconfigure --重新配置 9 go 10 sp_configure 'xp_cmdshell', 1 11 go 12 reconfigure 13 go 14 15 16 --//2,建立临时表保存临时信息 17 --if not exists(select * from tempdb..sysobjects where id=OBJECT_ID('tempdb..#tb01')) --ok 18 --if not exists(select * from tempdb..sysobjects where id=OBJECT_ID('tempdb..#tb01') and type='U') --ok 19 if (OBJECT_ID('tempdb..#tb01') is not null) 20 drop table #tb01 --drop table tempdb..#tb01 --ok too 21 create table #tb01([dosCMDResult] varchar(4000)) --save DOS cmd result 22 23 24 --//3,检查指定的路径是否存在,如果不存在则建立之,存在则提示 25 declare @strPath varchar(4000) 26 declare @dosCMD varchar(50) 27 declare @cmdLine varchar(4000) 28 set @strPath = 'c:\msSQLDBS' --指定路径 根据实际情况进行修改 29 set @dosCMD = 'dir ' --dos cmd 30 set @cmdLine = @dosCMD+@strPath 31 insert into #tb01 exec master..xp_cmdshell @cmdLine 32 select * from #tb01 33 if exists(select 1 from #tb01 where dosCMDResult in ('系统找不到指定的文件。','找不到文件','系统找不到指定的路径。')) --路径不存在
-- lin 原文为 dosCMDResult = '找不到文件' 但经过实际测试当父级目录不存在时结果为'系统找不到指定的文件。'和'系统找不到指定的路径。' 因此对where 条件进行合并 以应对不同情况34 begin 35 set @dosCMD = 'md ' 36 set @cmdLine = @dosCMD + @strPath 37 exec master..xp_cmdshell @cmdLine 38 --更多操作,比如在指定路径下建立某数据库,然后建立相关表等等 39 end 40 else --路径存在 41 begin 42 print char(13)+'路径:' + @strPath + ' 已经存在' 43 end 44 45 46 --//4,释放相关系统资源和恢复安全问题 47 drop table #tb01 48 set @cmdLine = null 49 set @dosCMD = null 50 set @strPath = null 51 go 52 53 sp_configure 'xp_cmdshell', 0 54 go 55 reconfigure 56 go
-