December 19, 2024 at 8:13 pm
I created a small procedure that reads the backup file and restores the DB daily. But when I execute the procedure Exec RestoreDatabaseFromLatestBackup @BackupPath = 'D:\Backup', @DatabaseName = 'TestDB', I get the following error
Error occurred: The name 'Restore Database TestDB from Disk = 'D:\Backup\Backup.bak' With Replace, keep_cdc' is not a valid identifier
But when I copy the error and run it in a different window, I am able to restore the DB successfully. Can someone help me troubleshoot the issue?
The code is attached with this question.
CREATE PROCEDURE RestoreDatabaseFromLatestBackup
@BackupPath NVARCHAR(500),
@DatabaseName NVARCHAR(128)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @LatestBackupFile NVARCHAR(500);
DECLARE @cmd NVARCHAR(MAX);
DECLARE @RestoreSQL NVARCHAR(MAX);
BEGIN TRY
IF @BackupPath IS NULL OR @BackupPath = ''
BEGIN
RAISERROR('Backup path is not provided.', 16, 1);
RETURN;
END
CREATE TABLE #BackupFiles (FileName NVARCHAR(500));
SET @cmd = 'DIR "' + @BackupPath + '\*.bak" /B';
INSERT INTO #BackupFiles (FileName)
EXEC xp_cmdshell @cmd;
SELECT TOP 1 @LatestBackupFile = FileName
FROM #BackupFiles
WHERE FileName IS NOT NULL
AND FileName <> ''
AND FileName LIKE '%.bak';
DROP TABLE #BackupFiles;
IF @LatestBackupFile IS NULL
BEGIN
RAISERROR('No backup file found in the specified directory.', 16, 1);
RETURN;
END
SET @LatestBackupFile = CONCAT(@BackupPath, '\', @LatestBackupFile);
SET @RestoreSQL = N'
RESTORE DATABASE [' + @DatabaseName + N']
FROM DISK = ''' + @LatestBackupFile + N'''
WITH REPLACE, Keep_cdc';
EXEC(@RestoreSQL);
END TRY
BEGIN CATCH
PRINT 'Error occurred: ' + ERROR_MESSAGE();
END CATCH
END;
GO
December 19, 2024 at 8:31 pm
This smells like a permissions issue for the SP. I am not anywhere I can test this but I suspect you will need to sign the SP and then have a certificate login in the master database that is a member of dbcreator.
December 19, 2024 at 9:28 pm
I have admin rights on the test server.
December 20, 2024 at 1:40 am
For starters, change this...
DECLARE @cmd NVARCHAR(MAX);
... to this ...
DECLARE @cmd NVARCHAR(4000);
Then see the following for why...
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply