Thursday, December 1, 2011

SQL Script to move files from one folder to another(newly created) folder

Hello All,

Back with another SQL script.
you have might observed that you have to manually copy files from one folder another folder(newly created folder) on windows .This might take lot of time and you have to keep monitoring it.

You will feel like this process must be automated so here SQL script which will create new folder and move files from one folder to newly created folder on same machine.

I came across a situation where i need to move files from X folder to Y folder but I need to create  folder with current date name in Y folder and move files in that folder only.


EXEC
master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE
EXEC
master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE

DECLARE @cmd nvarchar(500), @folderName varchar(100),@move varchar(100),@destinationpath varchar(50)

SET @folderName = Newfolder_' + REPLACE(CONVERT(varchar(10), GETDATE(), 101), '/', ''

SET @cmd = 'mkdir D:\destination\' + @folderName

EXEC master..xp_cmdshell @cmd   --- this will create folder(newfolder_mmddyyy)

set @destinationpath='D:\destination\'+@folderName
set @move ='move d:\source\* '+ @destinationpath

exec master.dbo.xp_cmdshell @move  ---this will move files to newly created folder


This script will move all files from D:\Source to D:\Destination (Newly created folder)
Newly created folder will be Newfolder_mmddyyyy.

YOu can use this process and make more processed automated which will reduce your manual work.


Get back to me if you need more help in this.

6 comments:

  1. Hi
    Thanks for the post. I Want to check if a particular folder exists based on my key value and create if it doesnt exist and move file. If it already exists just move file. How do we achieve this using T-SQL.

    ReplyDelete
  2. Thank u its very useful but can u advise me how to schedule this script to run daily

    ReplyDelete
  3. Hello Amit,

    I tried this code but its giving me this output :

    The device is not ready.
    Null

    What can i do?

    ReplyDelete
  4. Please do reply

    ReplyDelete
  5. This Code is very useful.Thank u very much..

    ReplyDelete