简体   繁体   中英

Restore SQL Server database on a remote server using C#

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.

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM