引自http://blog.csdn.net/htl258/article/details/5696591,覺得挺有用
USE mydb GO --1.查詢當前資料庫的邏輯檔案名稱 SELECT FILE_NAME(1) AS 'File Name 1', FILE_NAME(2) AS 'File Name 2'; --或通過以下語句查詢: --SELECT name FROM sys.database_files /* File Name 1 File Name 2 ------------------- -------------------- mydb mydb_log (1 行受影響) */ --2.修改資料檔案或記錄檔的邏輯名稱 ALTER DATABASE [mydb] MODIFY FILE ( NAME = mydb, NEWNAME = new_mydb ) ALTER DATABASE [mydb] MODIFY FILE ( NAME = mydb_log, NEWNAME = new_mydb_log ) --查詢更改後的名稱: SELECT FILE_NAME(1) AS 'File Name 1', FILE_NAME(2) AS 'File Name 2'; /* File Name 1 File Name 2 ------------------- -------------------- new_mydb new_mydb_log (1 行受影響) */ --3.若要將資料檔案或記錄檔移至新位置,先OFFLINE把檔案MOVE到相應的位置,然後再ONLINE -- 詳細參考以下步驟 --3.1 查詢資料檔案或記錄檔當前存放路徑: SELECT physical_name FROM sys.database_files /* physical_name ------------------------------------------------------------------------------------------- D:/Program Files/Microsoft SQL Server/MSSQL10.MSSQLSERVER/MSSQL/DATA/mydb.mdf D:/Program Files/Microsoft SQL Server/MSSQL10.MSSQLSERVER/MSSQL/DATA/mydb_log.ldf (2 行受影響) */ --3.2 移動路徑 USE [master] GO --3.2.1 關閉所有進程 DECLARE @str VARCHAR(500); SET @str = ''; SELECT @str = @str + 'KILL '+RTRIM(spid)+';'+CHAR(13)+CHAR(10) FROM master.dbo.sysprocesses WHERE dbid=DB_ID('mydb'); EXEC(@str); GO --3.2.2 設定資料庫離線 ALTER DATABASE [mydb] SET OFFLINE GO --3.2.3 移動資料檔案與記錄檔(為確保資料安全,建議改move為copy,複製成功後再刪除源檔案) EXEC master..xp_cmdshell 'move "D:/Program Files/Microsoft SQL Server/MSSQL10.MSSQLSERVER/MSSQL/DATA/mydb.mdf" "E:/DBTEST"',NO_OUTPUT EXEC master..xp_cmdshell 'move "D:/Program Files/Microsoft SQL Server/MSSQL10.MSSQLSERVER/MSSQL/DATA/mydb_log.LDF" "E:/DBTEST"',NO_OUTPUT GO --3.2.4 設定新的儲存路徑 ALTER DATABASE [mydb] MODIFY FILE (NAME = new_mydb,FILENAME = 'E:/DBTEST/mydb.mdf') ALTER DATABASE [mydb] MODIFY FILE (NAME = new_mydb_log,FILENAME = 'E:/DBTEST/mydb_log.ldf') GO --3.2.5 設定資料庫聯機 ALTER DATABASE [mydb] SET ONLINE GO --3.2.6 查詢新的路徑 USE mydb GO SELECT physical_name FROM sys.database_files /* physical_name ------------------------------ E:/DBTEST/mydb.mdf E:/DBTEST/mydb_log.ldf (2 行受影響) */