如何用SQL语句检测某路径是否存在和创建相关路径

在DB 操作时有时需要利用SQL语句检测某路径是否存在,不存在则创建之,这里涉及到几个方面,分别说明如下

检测原理主要是利用系统的xp_cmdshell存储过程执行DOS命令,过程中的信息可以保存在一个临时表中,查询该表即可知道DOS命令的执行结果,从而判断该路径是否存在,进而执行相关的操作,这里xp_cmdshell涉及到安全问题,首先需要dbo权限开启,具体操作如下,以下以SQL Server 2008为例:

use master
go

--//1,涉及安全问题,(用DBO权限用户)开启使用xp_cmdshell存储过程的权限
--SQL Server blocked access to procedure 'xp_cmdshell'
sp_configure 'show advanced options', 1
go
reconfigure --重新配置
go
sp_configure 'xp_cmdshell', 1
go
reconfigure
go


--//2,建立临时表保存临时信息
--if not exists(select * from tempdb..sysobjects where id=OBJECT_ID('tempdb..#tb01')) --ok
--if not exists(select * from tempdb..sysobjects where id=OBJECT_ID('tempdb..#tb01') and type='U') --ok
if (OBJECT_ID('tempdb..#tb01') is not null)
drop table #tb01  --drop table tempdb..#tb01 --ok too
create table #tb01([dosCMDResult] varchar(4000)) --save DOS cmd result


--//3,检查指定的路径是否存在,如果不存在则建立之,存在则提示
declare @strPath varchar(4000)
declare @dosCMD varchar(50)
declare @cmdLine varchar(4000)
set @strPath = 'c:\msSQLDBS' --指定路径
set @dosCMD = 'dir ' --dos cmd
set @cmdLine = @dosCMD+@strPath  
insert into #tb01 exec master..xp_cmdshell @cmdLine
select * from #tb01
if exists(select 1 from #tb01 where dosCMDResult = '找不到文件') --路径不存在
begin	
	set @dosCMD = 'md '
	set @cmdLine = @dosCMD + @strPath
	exec master..xp_cmdshell @cmdLine
	--更多操作,比如在指定路径下建立某数据库,然后建立相关表等等
end
else  --路径存在
begin
	print char(13)+'路径:' + @strPath + ' 已经存在'
end


--//4,释放相关系统资源和恢复安全问题
drop table #tb01
set @cmdLine = null
set @dosCMD = null
set @strPath = null
go

sp_configure 'xp_cmdshell', 0
go
reconfigure
go


在执行过程中,涉及修改数据选项,如果安装杀毒软件,则会弹出提示,允许修改即可。

记下方便日后直接查看,懒人计划,呵呵。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值