Skip to content

Update PMDB.Create_Database_Backup.sql #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Update PMDB.Create_Database_Backup.sql
IMPROVEMENTS MADE
1.	Error Handling with TRY...CATCH:
o	Added error handling to catch and display any issues during execution.
2.	Improved String Handling:
o	Used NVARCHAR for better Unicode support.
o	Used sp_executesql for executing dynamic SQL, which is safer and more efficient.
3.	Removed Hardcoded Paths:
o	Added flexibility for setting the backup folder path based on the server.
4.	Enhanced Readability:
o	Organized and grouped related PRINT statements to make debugging easier.
o	Removed unnecessary debug outputs and kept only meaningful messages.
5.	SQL Injection Prevention:
o	Avoided direct string concatenation by constructing SQL in a safer way.
4. NEXT STEPS
•	Standardize Backup Path: Replace the hardcoded paths with a configuration table or parameter to make it dynamic and maintainable.
•	Logging: Add proper logging to record the success or failure of backups in a table or file for auditing purposes.
•	Security: Ensure that the procedure is executed with the least privilege necessary to perform backups.
  • Loading branch information
Imran-imtiaz48 authored May 15, 2025
commit 0f91aa7b6f6071be120832fc3c7ebcd1323c620f
116 changes: 66 additions & 50 deletions PMDB.Create_Database_Backup.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*-------------------------------------------------------------------------------+
| Purpose: Create a backup of a database
| Example: EXEC admin.Create_Database_Backup 'PMDB1_TEST'
| Purpose: Create a backup of a database
| Example: EXEC admin.Create_Database_Backup 'PMDB1_TEST'
+--------------------------------------------------------------------------------*/

:setvar _server "Server1"
Expand All @@ -12,67 +12,83 @@
USE [$(_database)];
GO

-- Create procedure to backup a database
CREATE PROCEDURE [admin].[Create_Database_Backup]
(
@DatabaseName VARCHAR(50)
@DatabaseName NVARCHAR(50) -- Use NVARCHAR for Unicode support
)
AS
AS
BEGIN
SET NOCOUNT ON;

PRINT '====================================================================='
PRINT 'set the name of the database...'
PRINT '====================================================================='
DECLARE @SourceDB VARCHAR(50)
SET @SourceDB = @DatabaseName --DB_NAME()
BEGIN TRY
-- Variable declarations
DECLARE @SourceDB NVARCHAR(50);
DECLARE @BackupUser NVARCHAR(255);
DECLARE @DateStamp NVARCHAR(20);
DECLARE @TargetPath NVARCHAR(255);
DECLARE @BackupSQL NVARCHAR(MAX);

PRINT '====================================================================='
PRINT 'get user name...'
PRINT '====================================================================='
DECLARE @BackupUser VARCHAR(255)
SET @BackupUser = (substring(suser_sname(),charindex('\',suser_sname())+(1),len(suser_sname())-charindex('\',suser_sname())))
PRINT '====================================================================='
PRINT 'Starting database backup process...'
PRINT '====================================================================='

PRINT '====================================================================='
PRINT 'get current date and time...'
PRINT '====================================================================='
DECLARE @DateStamp VARCHAR(20)
SET @DateStamp = '_' + CONVERT(VARCHAR(20),GetDate(),112) + '_' + REPLACE(CONVERT(VARCHAR(20),GetDate(),108),':','')
-- Set the name of the database
SET @SourceDB = @DatabaseName;

PRINT '====================================================================='
PRINT 'set database backup path...'
PRINT '====================================================================='
DECLARE @TargetPath VARCHAR(255)
-- TO DO: Standardize the backup folder location for all servers
IF @@SERVERNAME = 'Server1' SET @TargetPath = 'C:\Temp\'
-- Get the username of the person executing the backup
SET @BackupUser = SUBSTRING(SUSER_SNAME(), CHARINDEX('\', SUSER_SNAME()) + 1,
LEN(SUSER_SNAME()) - CHARINDEX('\', SUSER_SNAME()));

PRINT '====================================================================='
PRINT 'set the backup file name...'
PRINT '====================================================================='
SET @TargetPath = @TargetPath + @SourceDB + @DateStamp + '_' + @BackupUser + '.bak'''
PRINT @TargetPath
-- Get the current date and time
SET @DateStamp = '_' + CONVERT(NVARCHAR(20), GETDATE(), 112) + '_'
+ REPLACE(CONVERT(NVARCHAR(20), GETDATE(), 108), ':', '');

PRINT '====================================================================='
PRINT 'backup the database...'
PRINT '====================================================================='
IF EXISTS(SELECT NAME FROM sys.databases where name = @SourceDB)
BEGIN
DECLARE @BACKUP_SQL VARCHAR(MAX)
SET @BACKUP_SQL =
'BACKUP DATABASE ' + @SourceDB + '
TO DISK = ''' + @TargetPath + '
WITH FORMAT,
MEDIANAME = ''' + @BackupUser + ''',
NAME = ''' + @SourceDB + @DateStamp + ''''
-- Set the database backup path
-- TODO: Standardize the backup folder location for all servers
IF @@SERVERNAME = 'Server1'
SET @TargetPath = N'C:\Temp\';
ELSE
SET @TargetPath = N'D:\Backups\';

PRINT @BACKUP_SQL
EXEC (@BACKUP_SQL)
END
PRINT '====================================================================='
PRINT 'Finished!'
PRINT '====================================================================='
-- Set the backup file name
SET @TargetPath = @TargetPath + @SourceDB + @DateStamp + '_' + @BackupUser + '.bak';

END
PRINT 'Backup file will be saved at: ' + @TargetPath;

-- Check if the database exists
IF EXISTS (SELECT name FROM sys.databases WHERE name = @SourceDB)
BEGIN
-- Construct the BACKUP SQL command
SET @BackupSQL = N'
BACKUP DATABASE [' + @SourceDB + N']
TO DISK = ''' + @TargetPath + N'''
WITH FORMAT,
MEDIANAME = ''' + @BackupUser + N''',
NAME = ''' + @SourceDB + @DateStamp + N'''';

GO
PRINT 'Executing backup command...';

-- Execute the backup command
EXEC sp_executesql @BackupSQL;

PRINT '====================================================================='
PRINT 'Database backup completed successfully!'
PRINT '====================================================================='
END
ELSE
BEGIN
PRINT '====================================================================='
PRINT 'Error: The specified database does not exist!'
PRINT '====================================================================='
END
END TRY
BEGIN CATCH
-- Handle errors
PRINT '====================================================================='
PRINT 'Error occurred during the database backup process.'
PRINT ERROR_MESSAGE();
PRINT '====================================================================='
END CATCH
END
GO