SQL语句如下:
1 USE [master] 2 3 GO 4 /* 相关参数说明 5 mydb:对应数据库名称,即要操作的数据库名称 6 7 */ 8 9 10 --3.2 移动路径 11 --查看对应数据库的日志文件和数据文件的相关信息 12 select database_id,name,physical_name AS CurrentLocation,state_desc,size from sys.master_files 13 where database_id=db_id(N‘mydb‘); 14 15 USE [master] 16 17 GO 18 19 20 --3.2.1 关闭所有进程 21 22 DECLARE @str VARCHAR(500); 23 24 SET @str = ‘‘; 25 26 SELECT @str = @str + ‘KILL ‘+RTRIM(spid)+‘;‘+CHAR(13)+CHAR(10) 27 28 FROM master.dbo.sysprocesses 29 30 WHERE dbid=DB_ID(‘mydb‘); 31 32 EXEC(@str); 33 34 GO 35 36 --3.2.2 设置数据库脱机 37 38 ALTER DATABASE mydb SET OFFLINE 39 40 GO 41 42 --3.2.3 移动数据文件与日志文件(为确保数据安全,建议改move为copy,复制成功后再删除源文件) 43 --此处为copy 44 45 EXEC master..xp_cmdshell ‘copy "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mydb.mdf" "F:\SQLServerDB\DATA"‘,NO_OUTPUT 46 47 EXEC master..xp_cmdshell ‘copy "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mydb_1.ldf" "F:\SQLServerDB\DATA"‘,NO_OUTPUT 48 49 GO 50 51 --3.2.4 设置新的存储路径 52 53 ALTER DATABASE mydb MODIFY FILE (NAME = LZMISGH40,FILENAME = ‘F:\SQLServerDB\DATA\mydb.mdf‘) 54 55 ALTER DATABASE mydb MODIFY FILE (NAME = LZMISGH40_log,FILENAME = ‘F:\SQLServerDB\DATA\mydb_1.ldf‘) 56 57 GO 58 --3.2.5 移动数据文件与日志文件(删除源文件) 59 EXEC master..xp_cmdshell ‘move "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mydb.mdf" "F:\SQLServerDB\DATA"‘,NO_OUTPUT 60 61 EXEC master..xp_cmdshell ‘move "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mydb_1.ldf" "F:\SQLServerDB\DATA"‘,NO_OUTPUT 62 63 GO 64 --3.2.6 设置数据库联机 65 --到此成功 66 67 ALTER DATABASE mydb SET ONLINE 68 69 GO