Sql-server – How to prevent users from overwriting databases when restoring

sql server

I don't want users to restore (with overwrite) on some specific databases. How can I inhibit from restoring over these databases?

Best Answer

It sounds like you want users to be able to restore databases from existing backup files, but only to new names.

I actually wouldn't give them permissions to restore databases at all - instead, create a stored procedure that will do the restores, and then grant permissions to the stored procedure rather than the user. Erland Sommarskog's article on granting permissions via certificates is fantastic. In a nutshell, you're going to:

  • Create a certificate
  • Create a login for that certificate
  • Grant the permissions to do restores to that login
  • Create a stored procedure with your own logic in it
  • Sign the stored proc with the certificate
  • Grant the users permissions to run the stored proc

It's way easier than it sounds. Then your stored procedure can have the business logic to check to make sure the database doesn't exist, plus you can put in more stuff like checking that there's enough drive space to safely restore the database, that they're putting it on the right drives, etc.

I can imagine even coding in a max number of databases that can be restored - for example, once we've hit 50 restored databases, don't allow any more - it's time for the user to clean house.

The stored proc would have input parameters for backup file, target database name, and folder path(s) for the restored files. You might find the logic in the MSSQLtips post on automatically generating restore scripts useful too - point it at a folder, and it gets the latest full, diff, and t-log backups and generates the restore statements.