2016-02-29 121 views
2

我在SQL Server中有一個存儲過程,用於檢查今天的備份文件(在其文件名中包含日期的文件)。檢查完成後,它將移動到robocopy這些文件到另一個文件夾。將變量傳遞到xp_cmdshell

挑戰:在此文件夾中,可能存在昨天或其他日期的文件。但只有今天的bak文件需要傳輸。

[email protected] allows me to capture the day of a month 
declare @day char(2) 
set @day = RIGHT('00' + CONVERT(NVARCHAR(2),DATEPART(DAY,GETDATE())),2) 
--print @day 

--In "MyFolder", it might containts files like 
--Project_backupfile_01_2006_02_28_001.bak 
--OR Project_backupfile_01_2006_02_27_001.bak 

--Currently I need to hard code 28 to represent 28th. How to pass in @day? 
EXEC master..xp_cmdshell 'dir d:\myfolder\Project*28*.bak/b' 

--Similarly, I would like to pass in @day variable so that the --Project_backupfile*02_*@day.bak 

-- Copy the backup fules from ftp to a local drive 
EXEC master..xp_cmdshell 'robocopy "d:\source" "E:\MSSQL\Restore\" Project_backupfile*_02_28*.bak /NFL /NDL /COPY:DAT /R:2 /W:1 /XO /E /Z /MT:10' 

回答

6

傳遞之前,使用一個變量來形成命令xp_cmdshell

declare @cmd varchar(100) 
select @cmd = 'dir d:\myfolder\Project*' + datename(day, getdate()) + '*.bak/b' 
-- print @cmd 
exec master..xp_cmdshell @cmd 

注:datename(day, getdate())會給你這個月的一天,一個字符串。

stuff(convert(varchar(5), getdate(), 101), 3, 1, '_')會給你02_28