上帝大脸 发表于 2016-11-5 05:51:02

sql server使用xp_cmdshell动态创建文件夹

  创建sql server存储过程动态创建文件夹,文件夹名根据创建时间决定
  
新窗口打开复制代码


[*]create procedure sp_createdir  
[*]    @dir nvarchar(4000),  
[*]as  
[*]begin  
[*]    declare @cmd nvarchar(4000)  
[*]    declare @now datetime  
[*]    set @now = getdate()  
[*]    set @dir = @dir + '\' +replace(replace(replace(convert(varchar, @now, 120), '-',''), ' ', ''),':', '') 
[*]    set @cmd = 'mkdir ' + @dir 
[*]    exec sp_configure 'show advanced options', 1    --允许配置高级选项 
[*]    reconfigure --重新配置 
[*]    exec sp_configure 'xp_cmdshell', 1  --启用xp_cmdshell 
[*]    reconfigure --重新配置 
[*]    exec xp_cmdshell @cmd 
[*] 
[*]    exec sp_configure 'xp_cmdshell', 0  --执行完成后出于安全考虑可以将xp_cmdshell关闭  
[*]end  


xp_cmdshell语法  
  
  xp_cmdshell {'command_string'} [, no_output]
  参数
  'command_string'
  是在操作系统命令行解释器上执行的命令字符串。command_string 的数据类型为 varchar(255) 或 nvarchar(4000),没有默认值。command_string 不能包含一对以上的双引号。如果由 command_string 引用的文件路径或程序名称中有空格,则需要使用一对引号。如果使用嵌入空格不方便,可考虑使用 FAT 8.3 文件名作为解决办法。
  no_output
  是可选参数,表示执行给定的 command_string,但不向客户端返回任何输出。
  返回代码值
  0(成功)或 1(失败)
  结果集
  执行下列 xp_cmdshell 语句将返回当前目录的目录列表。
  xp_cmdshell 'dir *.exe'
  行以 nvarchar(255) 列的形式返回。
  执行下列 xp_cmdshell 语句将返回随后的结果集:
  xp_cmdshell 'dir *.exe', NO_OUTPUT
  
  由于没有了解xp_cmdshell的参数定义,将@cmd参数设置为nvarchar(max),导致执行时出现错误“过程需要类型为'varchar'的参数'command_string'”。需要将@cmd定义为长度小于或等于4000的nvarchar类型变量。

  文章来源:http://www.itnose.net/detail/6023571.html
更多文章:http://www.itnose.net/type/96.html
页: [1]
查看完整版本: sql server使用xp_cmdshell动态创建文件夹