使用DBCC SHRINKFILE EMPTYFILE 选项迁移数据

本文介绍了如何使用DBCC SHRINKFILE的EMPTYFILE选项在不使数据库离线的情况下,迁移数据库文件。通过创建数据库、创建表、插入数据、添加新数据文件、清空旧文件并移除,展示了该方法的过程。注意,此方法无法移动系统对象,且性能可能不如detach和附加快,但优点是保持数据库在线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于DBCC SHRINKFILE EMPTYFILE的解释:

 

将指定文件中的所有数据迁移到同一文件组中的其他文件。由于数据库引擎不再允许将数据放在空文件内,因此可以使用ALTERDATABASE语句来删除该文件。

 

假设说我现在想将数据从一个磁盘移动到另外一个磁盘,在移动过程中不想数据库Offline,我们可以使用这个选项。下面是一个例子:

 

 

 --create demodatabase

create database test

on primary( name=test,filename='D:\testdata\test_primary.mdf'),

filegroup [seconday]

(name = testsecondary,filename='d:\testdata\test_secondary.ndf')

log on(name = test_log,filename='d:\testdata\test_log.ldf')

 

 

--create tableon secondary filegroup

use test

go

create table test(idint) on [seconday]

 

--Insert Demodata

 

declare @int int

set @int =0

while @int <100000

begin

insert into testvalues (@int )

set @int = @int+1

end

 

 --Add another dadtafile on secondary file group

 alter database test

 add file

 (name= test_secondary_new,filename='d:\testdata\test_secondary_new.ndf')

 to filegroup[seconday]

 

 

--Empty oldfile and data will move to another file in the same filegroup

 dbccshrinkfile('testsecondary',emptyfile)

 go

 --Show filesizeafter empty file

 dbccshowfilestats

 go

 --remove old file

 alter database test removefiletestsecondary

 

--drop demodatabase

 use master

 go

 drop database test

 

使用这个选项不能够移动系统对象,所以有局限性。另外性能上来讲肯定没有detach然后附近来的快,好处是整个数据库不会offline. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值