SQL Server Express 2008 not detaching auto-attached file?

瘦欲@ 提交于 2019-12-13 12:10:38

问题


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?


回答1:


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.



回答2:


    private static void DetachMdf(string dbServer, string dbName)
    {
        SqlConnection.ClearAllPools();
        using (SqlConnection conn = new SqlConnection(string.Format("Server={0};Database=master;Integrated Security=SSPI", dbServer)))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("sp_detach_db", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@dbname", dbName);
                cmd.ExecuteNonQuery();
            }
        }
    }


来源:https://stackoverflow.com/questions/1902054/sql-server-express-2008-not-detaching-auto-attached-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!