SQL Server 2008: Copy the file and rename it

I have a file inside a directory \\myServer\Admin\temp\testtemp.txt

I need to write TSQL for

  • Find the testtemp.txtfile.
  • If exists, create a copy and rename it to Copytesttemp.txt
  • If there is testtemp.txtalready in the above directory like this

    \\abcd\Admin\temp\Copytesttemp.txt
    
  • then delete it and recreate Copytesttemp.txt

How do I achieve this? Thank you

+5
source share
3 answers

You can use xp_cmdshell to run any DOS commands, for example,

declare @cmdstring varchar(1000)

set @cmdstring = 'copy \\myServer\Admin\temp\testtemp.txt \\myServer\Admin\temp\Copytesttemp.txt'
exec master..xp_cmdshell @cmdstring 

Just make sure xp_cmdshell is included in your installation.

+14
source

Create an SQL agent job that executes a script command to perform actions.

+3
source

EXEC master..xp_cmdshell 'COPY D:\T1\a.txt D:\T2\b.txt'

CMD

EXEC master..xp_cmdshell 'COPY D:\T1\abcd.txt D:\T2'
EXEC master..xp_cmdshell 'Move D:\T1\abcd.txt D:\T2'
0

All Articles