我的分离代码正确吗



我正在使用以下代码将我的DB从SQLServerexpress分离。如果它有什么问题,请告知。我在它上得到了一个错误。

"Could not locate entry in sysdatabases for database 'EXEC master'. No entry found with that name. Make sure that the name is entered correctly."

我使用的代码是

 Dim conn2 As New SqlConnection("Server=MyHomeServerSQLExpress;Database=master;Trusted_Connection=False;User ID=sa;Password=abc123;")
    Dim cmd2 As New SqlCommand("", conn2)
    cmd2.CommandType = CommandType.StoredProcedure
    cmd2.CommandText = "EXEC master.dbo.sp_detach_db @dbname = N'MyHomeDBTestPWD'"
    conn2.Open()
    cmd2.Connection = conn2
    cmd2.ExecuteNonQuery()

您的分配方式不对。当您只需要添加存储过程名称时,您正在CommandText中分配正确的SQL语句。然后,您需要在SqlCommand中添加一个Parameter

Dim cmd2 As New SqlCommand("", conn2) 
cmd2.CommandType = CommandType.StoredProcedure
cmd2.CommandText = "sp_detach_db"
cmd2.Parameters.AddWithValue("@dbname", "MyHomeDBTestPWD")
cmd2.ExecuteNonQuery()

如果您还想执行SQL语句,那么您只需要将CommandType更改为CommandType.Text

  1. 你的ConnectionString已经指向Master数据库,所以你不需要指定它。

    EXEC [dbo].[sp_detach_db] @dbname = N'MyHomeDBTestPWD'
    
  2. 如果你想指定数据库,你应该做这个

    EXEC [master].[dbo].[sp_detach_db] @dbname = N'MyHomeDBTestPWD'
    
  3. 你有错误的CommandType。如果您想按原样执行代码,请更改为CommandType.Text

CommandType.Text解决方案

Dim cmd2 As New SqlCommand("", conn2) 
cmd2.CommandType = CommandType.Text
cmd2.CommandText = "EXEC [dbo].[sp_detach_db] @dbname = 'MyHomeDBTestPWD'"
cmd2.ExecuteNonQuery()

CommandType.StoredProcedure解决方案

Dim cmd2 As New SqlCommand("", conn2) 
cmd2.CommandType = CommandType.StoredProcedure
cmd2.CommandText = "[dbo].[sp_detach_db]"
cmd2.Parameters.AddWithValue("@dbname", "MyHomeDBTestPWD")
cmd2.ExecuteNonQuery()

您最好使用Microsoft.SqlServer.Smo名称空间,它包含了使用数据库所需的所有内容。有一种特定的方法来连接/分离数据库

Server mServer = new Server(".");
mServer.KillAllProcesses("attach1");
mServer.DetachDatabase("attach1", true);

http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server.detachdatabase.aspx

最新更新