0

I need to write a C# program that restores a SQL Server database at a remote computer and I need to do this from local computer. My code is restoring database but I need to put path to backup .bak file at remote computer using "From Disk".

string sql =  "ALTER DATABASE [" + MyDatabaseName + "] ; Restore Database [" + MyDatabaseName + "] From Disk= '" + pathToBackupAtRemoteComputer +   "'WITH REPLACE;"
  1. When I delete database using SQL Server Management Studio and run code, I get an error that database does not exist or I don't have permission. I want to 1st: delete database, 2nd: create new database, 3rd: put data from backup file. Is there an option to write something like: "DROP SCHEMA IF NOT EXITS" or "CREATE DATABASE IF NOT EXIST" (like in MySQL)? I tried but it didn't work.

  2. Is there an option that I can use .bak file at my local computer (like in MySQL, when I transfer .sql file at local computer into string then restore database remotely)? Or maybe send .bak file from local to remote computer using C# application and do it automatically? I tried it out using PsExec, but there is no option to transfer file between two computers.

2 Answers 2

1

One way to delete database is by using the following:

USE master;
ALTER DATABASE [MyDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [MyDatabaseName] ;

This way, it will drop the database and the physical files .ldf and .mdf files. Another thing is you can also rename the database (and maybe compare the database with restored one)

A good article on renaming a database logical and physical files are here:

https://www.mssqltips.com/sqlservertip/1891/steps-to-rename-a-sql-server-database/

Sign up to request clarification or add additional context in comments.

Comments

0

DROP DATABASE IF EXISTS is possible in SQL Server in SQL Server 2016 onwards.

Because it is the SQL Server database engine performing the restore, the backup file must be accessible to the remote SQL Server and could be a UNC path.

1 Comment

Avoid using DROP. It changes the permission of the MDF file and then you require a ADMIN to fix the mess. It is better to DEATTACH the database then make a copy of the database in windows and then Reattached. You can actually have two copies of the same database by renaming the MDF file before Reattaching. This is really a great method for testing because you can test on the copy without affecting the original database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.