如何在代码中分离LocalDB(SQL Server Express)文件
发布时间:2020-05-24 17:12:20 所属栏目:MsSql 来源:互联网
导读:在部署中使用LocalDB .mdf文件时,您通常需要移动,删除或备份数据库文件. 首先将此文件分离为 simply deleting it will cause errors because LocalDB still keeps a registration of it是至关重要的. 那么如何在代码中分离LocalDB .mdf文件? 我不得不把几个
|
在部署中使用LocalDB .mdf文件时,您通常需要移动,删除或备份数据库文件.
那么如何在代码中分离LocalDB .mdf文件? 解决方法我不得不把几个地方的答案串起来,所以我将在这里发布:Mind,manually detaching the .mdf file from Visual Studio is possible after manually deleting it before detachment by going through SQL Server Object Explorer. ''' <summary>
''' Detach a database from LocalDB. This MUST be done prior to deleting it. It must also be done after a inadvertent (or ill advised) manual delete.
''' </summary>
''' <param name="dbName">The NAME of the database,not its filename.</param>
''' <remarks></remarks>
Private Sub DetachDatabase(dbName As String)
Try
'Close the connection to the database.
myViewModel.CloseDatabase()
'Connect to the MASTER database in order to excute the detach command on it.
Dim connectionString = String.Format("Data Source=(LocalDB)v11.0;Initial Catalog=master;Integrated Security=True")
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmd = connection.CreateCommand
'--Before the database file can be detached from code the workaround below has to be applied.
'http://web.archive.org/web/20130429051616/http://gunnalag.wordpress.com/2012/02/27/fix-cannot-detach-the-database-dbname-because-it-is-currently-in-use-microsoft-sql-server-error-3703
cmd.CommandText = String.Format("ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE",dbName)
cmd.ExecuteNonQuery()
'--
'--Now detach
cmd.CommandText = String.Format("exec sp_detach_db '{0}'",dbName)
cmd.ExecuteNonQuery()
'--
End Using
Catch ex As Exception
'Do something meaningful here.
End Try
End Sub (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- sql – 如何在多线程应用程序中获取DB2序列值
- sql-server-2005 – 在SQL Server中使用value()从xml列获取
- MySql 修改密码后的错误快速解决方法
- SQL Server SQL 时间格式化函数
- sql-server – 改变列SQL的DEFAULT约束
- sql-server – IsNumeric失败,出现“当前命令发生严重错误.
- MySQL中使用SQL语句查看某个表的编码方法
- sql-server – 如何在没有CLR的SQL Server 2008中调试存储过
- linq-to-sql – Linq to SQL和Linq to Objects查询相同吗?
- SQL在Where语句中使用别名
