Passing variable into xp_cmdshell

岁酱吖の 提交于 2019-12-12 16:30:03

问题


I have a stored procedure in SQL Server that checks for today's backup files (files that has a date in its filename). After checks, it will move on to robocopy these files to another folder.

The challenge: In this folder, there could be files from yesterday's or other dates. But only today's bak files are required for transfer.

--@day 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' 

回答1:


Use a variable to form the command before passing it to xp_cmdshell

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

Note: datename(day, getdate()) will give you the day of the month as a string.

stuff(convert(varchar(5), getdate(), 101), 3, 1, '_') will give you 02_28



来源:https://stackoverflow.com/questions/35691620/passing-variable-into-xp-cmdshell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!