sqlserver数据库移动数据库路径的脚本示例
use master
go
declare
@dbname sysname,
@destpath varchar(256)
declare @db table(
name sysname,
physical_name sysname)
begin try
select
@dbname = 'targetdatabasename', --input database name
@destpath = 'd:\sqldata\' --input destination path
-- kill database processes
declare @spid varchar(20)
declare curprocess cursor for
select spid
from sys.sysprocesses
where db_name(dbid) = @dbname
open curprocess
fetch next from curprocess into @spid
while @@fetch_status = 0
begin
exec('kill ' + @spid)
fetch next from curprocess
end
close curprocess
deallocate curprocess
-- query physical name
insert @db(
name,
physical_name)
select
a.name,
a.physical_name
from sys.master_files a
inner join sys.databases b
on a.database_id = b.database_id
and b.name = @dbname
where a.type <=1
--set offline
exec('alter database ' + @dbname + ' set offline')
--move to dest path
declare
@login_name sysname,
@physical_name sysname,
@temp_name varchar(256)
declare curmove cursor for
select
name,
physical_name
from @db
open curmove
fetch next from curmove into @login_name,@physical_name
while @@fetch_status = 0
begin
set @temp_name = right(@physical_name,charindex('\',reverse(@physical_name)) - 1)
exec('exec xp_cmdshell ''move "' + @physical_name + '" "' + @destpath + '"''')
exec('alter database ' + @dbname + ' modify file ( name = ' + @login_name
+ ', filename = ''' + @destpath + @temp_name + ''')')
fetch next from curmove into @login_name,@physical_name
end
close curmove
deallocate curmove
-- set online
exec('alter database ' + @dbname + ' set online')
-- show result
select
a.name,
a.physical_name
from sys.master_files a
inner join sys.databases b
on a.database_id = b.database_id
and b.name = @dbname
end try
begin catch
select error_message() as errormessage
end catch
go
推荐阅读
-
sqlserver数据库移动数据库路径的脚本示例
-
在sqlserver2005中安装sql server 2000的示例数据库northwind的方法
-
Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例
-
mssql sqlserver 使用sql脚本 清空所有数据库表数据的方法分享
-
图书管理系统的sqlserver数据库设计示例
-
nodejs基于mssql模块连接sqlserver数据库的简单封装操作示例
-
Mysql动态更新数据库脚本的示例讲解
-
[MSSQL]分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每
-
移动Sql Server数据库的脚本代码
-
Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例