SQL Server Express 2008 not detaching auto-attached file

sql serversql-server-2008sql-server-express

The MSDN documentation for SQLEXPRESS says:

When an application first establishes a connection from a running instance of SQL Server Express, SQL Server Express will automatically attach an .mdf file. When the user closes the application, SQL Server Express detaches the .mdf file from the instance.

This does not appear to be happening. If I replace the MDF file with a new one of the same name (after deleting the log file, of course) SQL Server Express will refuse to attach it.

I've tried just about every combination of connection string parameters possible, and it's driving me crazy. Any suggestions?

Best Answer

The detach/close does happen. If it wouldn't happen then you could not possibly replace the MDF file, because it would be in use. The documentation you quote is not entirely accurate. The correct documentation is at SQL Server 2005 Express Edition User Instances:

  • User instance databases have the Auto Close option set so that if there are no connections to a database for 8-10 minutes, the database shuts down and the file is closed. This happens automatically, but it can take a while, especially if connection pooling is enabled for your connections.
  • Detaching the database from the instance by calling sp_detach_db will close the file. This is the method Visual Studio uses to ensure that the database file is closed when the IDE switches between user instances.

If I'd venture a guess I'd say that the database is not detached but auto-closed, and replcing the MDF after deleting the LDF will be (rightfully) seen as an error when trying to open the database.

As side notes:

  • One should never ever delete the LDF file. If you want to replce the database, replace both the MDF and the LDF with the new ones.
  • Make sure you replace with proper MDF and LDF versions. SQL Server can upgrade a database, but can never downgrade it.
  • Get the error. If SQL Express refuses to attach a database, it will give a reason. Look into the RANU created ERRORLOG (in the user profile), the systen event log, or attach profiler to the user instance.