Click here to Skip to main content
15,559,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I'm trying to create an SP that backups a database however whenever I execute it the folder i'm trying to backup to remains empty. Here is my SP:

SQL
USE [HarvestMan_SoutheskFarm_03_05_22]
GO
/****** Object:  StoredProcedure [dbo].[BackupDatabases]    Script Date: 04/05/2022 09:58:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Will Sewell
-- Create date: 03-05-2022
-- Description:	Procedure to back up a database
-- =============================================
ALTER PROCEDURE [dbo].[BackupDatabases] 

@name VARCHAR(MAX) = 'HarvestMan_SoutheskFarm_03_05_22' -- DB NAME TO CREATE BACKUP
AS
BEGIN

DECLARE @path VARCHAR(256) -- path of backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name

SET @path = 'C:\Users\will.sewell\Documents\Database_Test'

-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
END
END
GO


What I have tried:

I have tried changing the drive that it is writing to.
I've copy and pasted the database name I want to backup to ensure no spelling mistakes.
I'm assuming it might be a permissions issue or a visible files in the folder.
Posted
Updated 4-May-22 0:35am

1 solution

Probably, it's the path.

SQL runs as an engine that you communicate with - and that engine does not run under your user, it has its own user and its own permissions.
So SQL can't access your files - "Users\will.sewell" is not accessible to the database engine at all.

Even if it was, that would only work for local SQL Server instances - remote ones can't even access your HDD, much less any folder on it! And local SQL instances are only there for development, so you don't mess with the production server!

So either create a folder on the server that can be accessed by all users (though that's a security risk all of its own and you will have to be careful about GDPR if you go that route) or better don't use an SP at all so that the location is actually flexible depending on where the installation is.

If you're trying to backup a local DB for development because your code is likely to trash it in a minute, then try this: Backing up an SQL Database in C#[^]
It's the way I do it!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900