SQL Server Management studio:
1. Select additional database operations
2. Select the additional button and the following interface will appear. Then, click the Add button.
3. Locate the database file, select the database you have detached or backed up, and click OK.
4. Add.
Added! Note: If the database already exists or has a duplicate name, The append database operation will fail!
The code for attaching the SMO database is as follows: // <summary>
/// Additional database
/// Note: if the database already exists, attaching will fail.
/// </Summary>
/// <Param name = "sqlconnectionstring"> </param>
Public static void attachdatabase (string sqlconnectionstring)
{
Using (sqlconnection connection = new sqlconnection (sqlconnectionstring ))
{
Server = new server (New serverconnection (connection ));
Stringcollection files = new stringcollection ();
Database currentdb = server. Databases ["test"];
If (currentdb = NULL)
{
// The master file is required
// The file name and suffix are case-insensitive. That is, the actual file is over. MDF, but it does not matter if it is set to over. MDF.
Files. Add (string. Format (@ "{0} \ {1}. MDF", "d: \" "," test "));
// Log can be left unspecified
Files. Add (string. Format (@ "{0} \ {1} _ log. LDF", "d: \" "," test "));
// Attachdatabase (Database Name, append database file path, database owner, attacexceptions option)
// The third setting is amazing! The attached database shows that the connected user in the connection is the owner TJ.
Server. attachdatabase ("Oye", files, "TJ", attacexceptions. None );
}
}
}