1、分离数据库
exec sp_detach_db dataname
eg: dataname:要分离的数据库名
2、附加数据库
1.exec sp_attach_single_file_db newdataname,mdfPath
eg:
newdataname:要附加上的新数据库名称(可以是原来的)
mdfPath='C:/Program Files/Microsoft SQL Server/MSSQL/Data/11_Data.MDF'
2.exec sp_attach_db newdataname,mdfPath,ldfPath
eg:
mdfPath='C:/Program Files/Microsoft SQL Server/MSSQL/Data/11_Data.MDF'
ldfPath='C:/Program Files/Microsoft SQL Server/MSSQL/Data/11_Log.LDF'
备注:不能操作本数据库
eg:
string DataName="aaa";
string strMdf="D://test1//test//Test_Data.MDF";
string strLdf="D://test1//test//Test_Log.LDF";
string strsql = "EXEC sp_attach_db
@dbname = '"+ DataName +"',
@filename1='"+ strMdf +"',
@filename2= '"+strLdf+"'";
SqlConnection myConn = new SqlConnection("Data Source=HUIQIN;Database=master;Persist Security Info=True;
UserID=sa;Password=sa");
SqlCommand myCommand = new SqlCommand(strsql, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
exec sp_detach_db dataname
eg: dataname:要分离的数据库名
2、附加数据库
1.exec sp_attach_single_file_db newdataname,mdfPath
eg:
newdataname:要附加上的新数据库名称(可以是原来的)
mdfPath='C:/Program Files/Microsoft SQL Server/MSSQL/Data/11_Data.MDF'
2.exec sp_attach_db newdataname,mdfPath,ldfPath
eg:
mdfPath='C:/Program Files/Microsoft SQL Server/MSSQL/Data/11_Data.MDF'
ldfPath='C:/Program Files/Microsoft SQL Server/MSSQL/Data/11_Log.LDF'
备注:不能操作本数据库
eg:
string DataName="aaa";
string strMdf="D://test1//test//Test_Data.MDF";
string strLdf="D://test1//test//Test_Log.LDF";
string strsql = "EXEC sp_attach_db
@dbname = '"+ DataName +"',
@filename1='"+ strMdf +"',
@filename2= '"+strLdf+"'";
SqlConnection myConn = new SqlConnection("Data Source=HUIQIN;Database=master;Persist Security Info=True;
UserID=sa;Password=sa");
SqlCommand myCommand = new SqlCommand(strsql, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
本文介绍如何使用 SQL Server 的存储过程 sp_detach_db 和 sp_attach_db 进行数据库的分离与附加操作,并提供了具体的执行示例代码。

1298

被折叠的 条评论
为什么被折叠?



