SQL Server Database Mobile database path script Example _mssql

Source: Internet
Author: User

Copy Code code as follows:

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.