Friday, September 5, 2008

SMO Detach Attach DataBase Sample

SqlConnection sqlConn = new SqlConnection(refDBConnectionString);
Server server = new Server(sqlConn.DataSource);
Database refDB = server.Databases[sqlConn.Database];
string refDBFilename = refDB.FileGroups[0].Files[0].FileName;
string refDBLogFilename = refDB.LogFiles[0].FileName;
string templateDBUnc = systemUnc + @"\SampleTemplate.mdf";
string templateDBLogUnc = systemUnc + @"\SampleTemplate.ldf";

// Detach Reference DB
server.DetachDatabase(sqlConn.Database, true);

// Copy and attach temp DB
FileInfo refDBUncFile = new FileInfo(refDBUnc);
string tempDBUnc = refDBUncFile.Directory.FullName + @"\SampleTempDev.mdf";
string tempDBLogUnc = refDBUncFile.Directory.FullName + @"\SampleTempDev.ldf";
File.Copy(refDBUnc, tempDBUnc, true);
File.Copy(refDBLogUnc, tempDBLogUnc, true);

// Re-attach the Reference DB
StringCollection refDBFiles = new StringCollection();
refDBFiles.Add(refDBFilename);
refDBFiles.Add(refDBLogFilename);
server.AttachDatabase(sqlConn.Database, refDBFiles);

No comments: