2012-05-17 3 views
2

C# 코드를 사용하여 SQL 데이터베이스를 복원하려고합니다. 백업이 정상적으로 작동하고 있습니다. 하지만 db를 복원하면 오류가 발생합니다. 이 작업에는 Microsoft.SqlServer.Management.Smo;을 사용하고 있습니다. { "System.Data.SqlClient.SqlError :이 세션에서 사용 중이기 때문에 RESTORE가 'TempDb'데이터베이스를 처리 할 수 ​​없습니다. 이 작업을 수행 할 때 master 데이터베이스를 사용하는 것이 좋습니다."}C# 코드를 사용하여 SQL 데이터베이스 복원

여러 게시물에서 데이터베이스를 마스터로 설정한다고합니다. 나는 또한 그것을 시도했다. 그러나 그것은 나에게 같은 오류를 준다. 연결 문자열 : connectionString = @ "server = (local); 초기 카탈로그 = 마스터, 통합 보안 = True;"; 데이터베이스가 다른 로그인에서 사용 여전히 같은

openFileDialog1.ShowDialog(); 
     string databaseName = "TempDb"; 
     Restore sqlRestore = new Restore(); 

     BackupDeviceItem deviceItem = new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File); 
     sqlRestore.Devices.Add(deviceItem); 
     sqlRestore.Database = databaseName; 

     DataConnection dataConnection = new DataConnection(); 
     ServerConnection connection = new ServerConnection(dataConnection.DataBaseConnection); 
     Server sqlServer = new Server(connection); 

     Database db = sqlServer.Databases[databaseName]; 
     sqlRestore.Action = RestoreActionType.Database; 
     String dataFileLocation = db.FileGroups[0].Files[0].FileName; 
     String logFileLocation = db.LogFiles[0].FileName; 
     db = sqlServer.Databases[databaseName]; 
     RelocateFile rf = new RelocateFile(databaseName, dataFileLocation); 


     sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation)); 
     sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation)); 
     sqlRestore.ReplaceDatabase = true; 
     sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete); 
     sqlRestore.PercentCompleteNotification = 10; 
     sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete); 
     sqlRestore.SqlRestore(sqlServer); 
     db = sqlServer.Databases[databaseName]; 
     db.SetOnline(); 
     sqlServer.Refresh(); 
+3

복원을위한 /stackoverflow.com/questions/3566632/cleaning-up-after-calls-to-smo-server-and-database). –

+0

고마워 ... 그 작품은 .... – udaya726

+0

우리는 SQl 서버 관리 스튜디오를 사용하여 데이터베이스를 복원 할 때 백업 세트를 선택할 수 있습니다. 이 코드를 사용하여 첫 번째 옵션 만 복원합니다. 구성 할 수 있습니까? – udaya726

답변

0

그것은 보이는 다음과 같이

내 코드입니다. 복원 전에 단일 사용자 모드로 전환 해보십시오. 정말 도움이됩니다. 동일한 연결 개체를 사용하여 데이터베이스를 단일 사용자 모드로 설정 한 다음 복원 한 다음 다중 사용자 모드로 되돌려 놓아야합니다./: 당신이 시도 할 수

,

SqlConnection connection = new SqlConnection("connection string"); 
SqlCommand cmd = new SqlCommand("ALTER DATABASE <database name> SET SINGLE_USER WITH ROLLBACK IMMEDIATE", connection); 

cmd.Connection.Open(); 
cmd.ExecuteNonQuery(); 

return connection; //to use the same connection for restore activity and setting it to multi user mode again 


//up on completion of restore activity, take the database to multi user mode. 
//ALTER DATABASE <database name> SET MULTI_USER 
0
this code For Restore Database,Please Type Code In C#: 

SqlConnection ObjConnection=new SqlConnection("Your Connection String"); 
ObjConnection.Open(); 
       SqlCommand ObjCommand = new SqlCommand(); 
       ObjCommand.Connection = ObjConnection; 
       ObjCommand.CommandText = "Use Master ALTER DATABASE YourDatabaseName SET     OFFLINE WITH ROLLBACK IMMEDIATE " + 
       "Restore Database YourDatabaseName From Disk='" + LblPath.Text + "'" + 
       " ALTER DATABASE YourDatabaseName SET ONLINE WITH ROLLBACK IMMEDIATE"; 
       ObjCommand.CommandType = CommandType.Text; 
       ObjCommand.ExecuteNonQuery(); 
Help:LblPath.Text is a Label Control Contain Path Backup Database You! 
Mojtaba From IRAN 
0

이 코드는 (HTTP [SMO 서버 및 데이터베이스에 대한 호출 후 정리]를 살펴 보자 데이터베이스를

var conString = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTRING"]; 
string strConnString = conString.ConnectionString; 
SqlConnection cs = new SqlConnection(strConnString); 

     try 
     { 
      cs.Open(); 
      String sqlquery = "Use Master ALTER DATABASE databasename SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE databasename FROM DISK ='" + txtRestoreFileLoc.Text + "' ALTER DATABASE databasename SET ONLINE WITH ROLLBACK IMMEDIATE"; 
      SqlCommand cmd = new SqlCommand(sqlquery, cs); 
      cmd.ExecuteNonQuery(); 
      cs.Close(); 
      cs.Dispose(); 
      MessageBox.Show("restore complete"); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 

     } 
관련 문제