Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Script to create datestamp folder causing issue Expand / Collapse
Author
Message
Posted Tuesday, December 8, 2009 2:26 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, June 5, 2013 2:44 AM
Points: 9, Visits: 271

I am trying to create date stamp folder and later move files to that folder through following script.
But when i execute script it create folder but as %folderdate% and not as datestamp.
where as when i execute three of the commands through command prompt it works fine. So can anyone help me to sort out this and tell where iam going wrong.

declare @setdate varchar (100)
declare @CreateDir varchar (100)
declare @Filemov varchar (100)

select @setdate='set folderdate=%date:~0,2%-%date:~3,2%-%date:~6,4%'
print @setdate
select @CreateDir='mkdir G:\Testing\test1\%folderdate%'
print @CreateDir
select @Filemov='move /Y G:\Testing\*.csv G:\Testing\test1\%folderdate%'
print @Filemov
exec master..xp_cmdshell @setdate
exec master..xp_cmdshell @CreateDir
exec master..xp_cmdshell @Filemov
Post #830488
Posted Tuesday, December 8, 2009 3:55 AM


Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: 2 days ago @ 4:56 AM
Points: 359, Visits: 924
I think its due to the fact that each call to xp_cmdshell spawns a new shell process and so the second call (2nd process) can't see the variable. Which explains why its works in the cmd shell as one statement.

You can try this, it works on my machine. Alter the path as required

declare @setdate varchar (100)
declare @CreateDir varchar (100)
declare @Filemov varchar (100)

--select @setdate='set folderdate=%date:~0,2%-%date:~3,2%-%date:~6,4%'
select @setdate = convert(varchar(11),getdate(),105)
print @setdate
select @CreateDir='mkdir C:\Test\' + @setdate
print @CreateDir
select @Filemov='move /Y C:\Test\*.txt C:\Test\' + @setdate
print @Filemov

exec master..xp_cmdshell @CreateDir
exec master..xp_cmdshell @Filemov

Once you're happy you may want to specify with no output if you don't want it to interfere with a batch?
Post #830526
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse