先上一個使用SQL 陳述式進行Detach和Attach資料庫的語句:
use mastergosp_detach_db 'TestDB'go use mastergosp_attach_db '1','C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB.mdf','C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB_log.ldf'go
用C#進行Detach和Attach資料庫,我想到的有兩種方法
1. 用SqlCommand執行上述語句,代碼如下:
using(SqlConnectionsc =newSqlConnection(txtConntionString.Text))
{
using(SqlCommandcmd =newSqlCommand(@"use master;
exec sp_detach_db 'TestDB'", sc))
{
if(sc.State ==ConnectionState.Closed)
sc.Open();
cmd.CommandType =CommandType.Text;
cmd.ExecuteNonQuery();
}
}
using(SqlConnectionsc =newSqlConnection(txtConntionString.Text))
{
using (SqlCommandcmd =newSqlCommand(@"use master;
exec sp_attach_db 'TestDB'
,'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB.mdf'
,'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB_log.ldf'", sc))
{
if(sc.State ==ConnectionState.Closed)
sc.Open();
cmd.CommandType =CommandType.Text;
cmd.ExecuteNonQuery();
}
}
需要注意的是SQL語句中的go在這裡換成了分號,SQL語句中不加exec也可以正常執行,而這裡必須加入exec
因為用到了SqlConnection,所以必須指定一個有效串連字串,在Detach時可以用TestDB這個資料庫作串連字串,但是在Attach時,就不用TestDB了,因為還未建立,這點在寫代碼時要注意,當然如果串連字串中使用的是master資料庫,那use master也可以省了
2. 使用SQL Server內建的Attach和Detach功能
這裡有用到SQL Server提供的幾個Dll
先加引用:
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
命名空間加:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Collections.Specialized;
代碼如下:
ServerConnection sc = new ServerConnection("ServerNameHere");//You can specify username and password here
Server server = newServer(sc);
server.DetachDatabase("TestDB",false);
ServerConnection sc = new ServerConnection("ServerNameHere");//You can specify username and password hereServer server = new Server(sc);
StringCollection files = new StringCollection();files.Add(@"C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB.mdf");files.Add(@"C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDB_log.ldf"); server .AttachDatabase("TestDB", files, AttachOptions.None);
在執行完後可以調用Server的Disconnect方法關閉串連。
在detach和attach資料庫時有一些選項,可以根據需要自己指定。
更新:
查看SQL Server協助文檔得知 sp_attach_db在今後可能棄用,建議使用create database,樣本如下:
USE master;GOsp_detach_db Archive;GO-- Get the SQL Server data pathDECLARE @data_path nvarchar(256);SET @data_path = (SELECT SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) FROM master.sys.master_files WHERE database_id = 1 AND file_id = 1);-- Execute CREATE DATABASE FOR ATTACH statementEXEC ('CREATE DATABASE Archive ON (FILENAME = '''+ @data_path + 'archdat1.mdf'') FOR ATTACH');GO
不過目前在SQL Server 2008中sp_attach_db還是可以正常使用的