Showing posts with label XP_CMDSHELL. Show all posts
Showing posts with label XP_CMDSHELL. Show all posts

Thursday, 28 May 2015

Sharing/Unsharing remote server's folder with remote stored procedure execution in SQL Server by serverku

Recently, when I was working with database backup plans and scheduling it on another server as this shared folder of the server should not be available to anyone after the backup process completion. I have created below script with stored procedure on remote server and run the stored procedure remotely from local server to share and unshare the remote server's folder. Please note xp_cmdshell and Ad Hoc Distributed Queries should be enabled on the server.

USE MASTER
GO

-- Creating shared
EXEC XP_CMDSHELL 'NET SHARE SharedFolder=E:\DatabaseBackups
/GRANT:Everyone,Full
/REMARK:"Database backups perform on another server"'
GO

-- Removing shared
EXEC XP_CMDSHELL 'NET SHARE SharedFolder /delete"'
GO

Tuesday, 28 April 2015

Copy database backup files using XCOPY command by serverku

Recently, when I was working database backups copy to external drives or whatever destination, I tried it with new solution using XCOPY command. Before that solution I was using XP_CMDSHELL command in SQL Server to copy database backup file to an external drive, also we should avoid using XP_CMDSHELL for security concern. So out of SQL server script\query and another tool, the solution came with XCOPY command which copy latest files or as per date specified, so later database backup files or the files created on or after the date specified as input. You can visit XCOPY command here.
Lets first share me the command which I am using to copy latest database backup files. Here I am using some variables in the code, but let’s share me script first, then I will explain the variables.
SET dwMONTH=%DATE:~4,2%
SET dwDAY=%DATE:~7,2%
SET dwYEAR=%DATE:~10,4%
SET dwDate=%dwMONTH%-%dwDAY%-%dwYEAR%

SET source=C:\DatabaseBackup
SET destination=\\externaldrive\DatabaseBackup\
SET extension=*.bak

XCOPY /Y %source%\%extension% %destination% /s /i /D:%dwDate%
You can see batch file created with the above code and the variables used inside and how they are integrated with final XCOPY command. After getting to run it will copy database backup files to an external drive or whatever destination using source, Destination, file extension (.bak\.trn here) and the date on or after the backup files created. Let’s implement and run it..
This code in batch files, copy all the files created Today with specified file type from source folders including sub folders to destination. So lets run batch and see what’s inside. Let's try with sample example and local drives,

Apart from XP_CMDSHELL command using in SQL Server, which methods you are using the database backup files to external drives? Please share here. I will post a further topic with a different method for the same. Hope you enjoyed it.