Error when creating sql database

549 views Asked by At

I deleted manually sql database file(myDB.mdf and myDB_log.ldf) When I want to create database with same name (myDB) I get the following error message.

System.Data.SqlClient.SqlException (0x80131904):Database 'myDB' already exists. Choose a different database name.

my code:

String str;
SqlConnection Conn = new SqlConnection("Server=.\\SQLEXPRESS;Integrated security=true;User Instance=True;database=master");
str = "CREATE DATABASE myDB " + 
      "ON PRIMARY " + "( NAME = N'myDB', FILENAME = N'" + Application.StartupPath + "\\myDB.mdf' , SIZE = 5120KB , FILEGROWTH = 1024KB )" + 
      "LOG ON" + "( NAME = N'myDB_log', FILENAME = N'" + Application.StartupPath + "\\myDB_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)";
SqlCommand Command = new SqlCommand(str, Conn);

how fix this by c# script?

2

There are 2 answers

4
Lukos On

You should not delete database files directly because they are referenced in the master database in SQL Server. If you can restore the files, do this and then delete the database from within SQL Server Management Studio or otherwise you will need to manually delete the database entries in the master database tables!

0
Muhammad Umair On

You may try to use to resolve the problem

EXEC sp_detach_db 'dbName', 'true';

the above said sp_detach detaches the database with skipchecks set to true