Question

I know that there are many similar questions in stackoverflow, but non of them totally satisfied my request?

1 - I DO NOT WANT TO ATTACH A DATABASE that contains 2 .mdf .ldf files
2 - The file is only a single .bak file
3 - i don`t want to use Microsoft SQL Management.
4 - i need it to be done programmatically ?( in my case c#)

Was it helpful?

Solution

You can restore a database by sending a T-SQL command (the same you would send a select query). For example:

restore database NameOfYourDb
from    disk = 'c:\backups\NameOfYourDb.bak'
with    recovery,
        move 'NameOfYourDb_Data' to 'c:\data\NameOfYourDb.mdf',
        move 'NameOfYourDb_Log' to 'c:\data\NameOfYourDb.log'

Two is the smallest number of files that can be stored in a .bak file. Every database has at least one data and one log file (with extension .mdf and .log respectively.)

Note that a restore is done by the SQL Server service. You have to supply the paths from the point of view of that service. The account SQL Server is running under needs read access to the .bak file and write access to the .mdf and .log files.

OTHER TIPS

Take a look at SMO Objects in the .NET library. There is a restore object here that you can use to restore a database. SQL Server Management Studio is built using this SMO objects, so anything you can do with SSMS you can do with C#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top