在其他计算机上还原数据库需要创建主密钥

时间:2018-12-26 14:48:32

标签: c# sql-server sql-server-2008-r2

进行备份然后在另一台计算机上还原时,出现错误

  

请在执行此操作之前在数据库中创建主密钥或在会话中打开主密钥。

我正在使用SQL Server 2008 R2。首先,备份或还原例程是否存在问题?还是在尝试打开对称密钥时采取行动? 我可以张贴您要求的任何代码示例。这是我的备份例程:

FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
  {

      using (SqlConnection connetion = new SqlConnection(Connection.connectionString))
      using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE [" + Connection.Database + "] TO  DISK = '" + dlg.SelectedPath + "\\myBackup.bak'", connetion))
      {
        connetion.Open();
        cmd.ExecuteNonQuery();
      }
}

我还试图在还原后删除我的对称密钥,但它不会将其删除。

 using (SqlConnection connection = new SqlConnection(Connection.connectionString))
                {
                    connection.Open();
                    using (SqlCommand cmd = new SqlCommand("ALTER DATABASE [" + Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", connection))
                        cmd.ExecuteNonQuery();

                    using (SqlCommand cmd = new SqlCommand("USE MASTER RESTORE DATABASE [" + Connection.Database + "] FROM DISK = '" + openFileDialog1.FileName + "' WITH REPLACE", connection))
                        cmd.ExecuteNonQuery();


                    using (SqlCommand cmd = new SqlCommand("IF  EXISTS (SELECT * FROM sys.certificates WHERE name = 'PasswordEncryption') select 1 else select 0", connection))
                        if (Convert.ToInt32(cmd.ExecuteScalar()) == 1)
                        {

                            using (SqlCommand cmd2 = new SqlCommand("USE MASTER DROP SYMMETRIC KEY Customer_Password;", connection))
                                cmd2.ExecuteNonQuery();



                        }


                }

0 个答案:

没有答案