完整的利用xp_cmdshell在T-SQL中执行类似创建目录的功能

 
-- 从SQL Server 2005 开始,SQL Server引入的 xp_cmdshell 选项是服务器配置选项,
-- 使系统管理员能够控制是否可以在系统上执行 xp_cmdshell 扩展存储过程。
-- 默认情况下,xp_cmdshell 选项在新安装的软件上处于禁用状态
declare @config table(name varchar(512), minimum int, maximum int, config_value int, run_value int)
insert into @config EXEC sp_configure
-- 判断是否开启了高级设置,如果未开启,开启之
declare @advCfg int = 0;
if exists (select * from @config where name = 'show advanced options')
	select @advCfg = config_value from @config where name = 'show advanced options'
if (@advCfg = 0) begin
	EXEC sp_configure 'show advanced options', 1
	RECONFIGURE;
	delete @config;
	insert into @config EXEC sp_configure
end;
-- 判断是否开启了执行 xp_cmdshell 扩展存储过程的功能,如果未开启,开启之
declare @xpcmd int = 0;
if exists (select * from @config where name = 'xp_cmdshell')
	select @xpcmd = config_value from @config where name = 'xp_cmdshell'
if (@xpcmd = 0) begin
	EXEC sp_configure 'xp_cmdshell', 1
	RECONFIGURE
end;

--在这里开始执行需要调用xp_cmdshell执行的方法,比如在T-SQL中创建磁盘文件目录
declare @path nvarchar(1000) = 'E:\BackDDDD'
declare @temp table(a int,b int,c int)   
insert @temp exec master..xp_fileexist @path 
if not exists(select * from @temp where b=1)
	exec xp_cmdshell 'mkdir E:\BackDDDD'

-- 如果执行开始前,人工开启了执行 xp_cmdshell 扩展存储过程的功能,需要在执行结束后关闭高级配置项目
if (@xpcmd = 0) begin
	EXEC sp_configure 'xp_cmdshell', 0
	RECONFIGURE
end;
-- 如果执行开始前,人工开启了高级配置,需要在执行结束后关闭高级配置项目
if (@advCfg = 0) begin
	EXEC sp_configure 'show advanced options', 0
	RECONFIGURE;
end;


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值