Search code examples
c#sql-serverwinformsdatabase-backups

Get the name of db from sql express


I have used this connection string to connect my sql database to sql express automatically:

Data Source=.\SQLEXPRESS; AttachDBFileName=|DataDirectory|\DB\MyDBName.mdf; User ID=sa;Password=MyPass;Persist Security Info=True

everything works fine, but the problem is when i want to get backup from my db.The sql express changes the name of db when attach it so in backup query i get this error:

Database 'MyDBName' does not exist.Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.

My backup query is:

BACKUP DATABASE [MyDBName] TO DISK=N'" + filePath + "' WITH NOFORMAT, INIT, SKIP, NOREWIND, NOUNLOAD, STATS = 10;

Is there any way to get the current name of my db from sql express OR set the name of my db when attached automatically to sql express?


Solution

  • First execute the following query and get database name

    SELECT DB_NAME() AS DataBaseName
    

    i.e

     SqlCommand cmd = new SqlCommand("SELECT DB_NAME() AS dbName",your_connection);
     string name = cmd.executeScalar().ToString();
     //now do what ever you want to with db name