Prevent overwriting of a database while Restoring manually

  • I want to restore a database to my server, but a database with the same name already exists on my server. In this case, I don’t want to manually change the name of the database while restoring. I want SQL Server to prompt or provide an option to prevent direct restoration, so the existing database is not overwritten. Default renaming during the restore process is also acceptable.

    I have tried the following approaches without success:

    1. Disabling the 'Overwrite the existing database' option. But , did not

    work

    https://dba.stackexchange.com/questions/254796/restore-a-database-with-a-different-name-on-the-same-server

    2. Enabling the 'Prompt before restoring each backup' option .

    https://stackoverflow.com/questions/19624189/backup-log-cannot-be-performed-because-there-is-no-current-database-backup

    Unfortunately, this approach has also not worked as this setting is for multiple database restore case.

    Are there any settings available to prompt before overwriting the database or to prevent overwriting a database with the same name?

  • First, SQL Server doesn't do anything with prompting. That's SSMS or your IDE. Everything submitted to the SQL Server instance is code. If you are in SSMS and use the restore database  and click OK, code is sent to the database engine. You can see this by clicking the Script button at the top. It's important to understand this to realize what is happening.

    In SSMS there are sometimes not prompts for actions. Restoring the same database from an existing backup is one of these. When a database backup is taken, there is a DB guid. If you restore over the existing db from a backup with the matching guid, no error is generated and REPLACE is not needed.

    You can see this doc'd in the REPLACE command: https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-transact-sql?view=sql-server-ver16#REPLACEoption

     

    There is no setting in SSMS, AFAIK, to prompt you in any way. The way to better prevent issues is to use code and explicitly set code to restore copies of a db if you need them.

     

  • I think there should be an explicit "NO REPLACE" option, but MS doesn't have it.

    Instead, you can check for the db exiting before you issue the RESTORE DATABASE command:

    IF EXIST(SELECT * FROM sys.databases WHERE name = 'your_db_name')

    PRINT 'Cannot restore because database already exists!'

    ELSE

    BEGIN

    RESTORE DATABASE ...

    END /*ELSE*

    SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply