Thursday, September 8, 2016

Dynamically Create a Folder for Each Database In Server

I Need to Create Folder For Each Database in a particular server.I like to have a specific folder structure to hold the backup files for each database.  See below:

                       D:\Backup\Server\Instance\BabjiDB
                     D:\Backup\Server\Instance\NaveenDB
                     D:\Backup\Server\Instance\JaipalDB

So we need to maintain each DB backup in separate folder,Check Below T-SQL code 


DECLARE
       @BaseFolder nvarchar(128)
      ,@DatabaseFolder nvarchar(256)
      ,@DbName sysname
     
-- Only one input parameter needed from the user.
SET @BaseFolder = 'D:\Backup';

DECLARE Db CURSOR FOR
SELECT name FROM sys.databases WHERE name <> 'tempdb';

OPEN Db;
FETCH NEXT FROM Db INTO @DbName;
WHILE @@FETCH_STATUS = 0
BEGIN
      -- Dynamically create a folder for each database.
      SET @DatabaseFolder = @BaseFolder + '\'
      + CONVERT(nvarchar,SERVERPROPERTY('MachineName')) + '\'
      + ISNULL(CONVERT(nvarchar,SERVERPROPERTY('InstanceName')),'DEFAULT')
      + '\' + @DbName;
      EXEC master.sys.xp_create_subdir @DatabaseFolder;
      FETCH NEXT FROM Db INTO @DbName;
END

-- Clean up
CLOSE Db;
DEALLOCATE Db;
GO


No comments:

Post a Comment