SQL Server表分区案例

 

--学习创建表分区脚本
/*
SQL SERVER 2005中以上版本,终于引入了表分区,就是说,当一个表里的数据很多时,可以将其分拆到
多个的表里,大大提高了性能。下面举例子说明之
*/

-------------------------------------------------------------
/*
比如,在D盘下建立如下几个目录
D:\DataDB\Primary
D:\DataDB\FG1
D:\DataDB\FG2
D:\DataDB\FG3
D:\DataDB\FG4

其中primary存放的是主数据库文件,其他FG1--FG4存放四个单独的文件组,可以见创立数据库
TestDB,如下

*/
use master
go

if exists(select name from sys.databases where name=N'TestDB')
drop database TestDB
go
create database TestDB
on primary
(name='Test DB Primary FG',
filename='d:\DataDB\Primary\Data Test DB Primary FG.mdf',
size=5,
maxsize=500,
filegrowth=1),
FILEGROUP [Data Test DB FG1]
(name='Data Test DB FG1',
filename='d:\DataDB\FG1\Data Test DB FG1.ndf',
size=5,
maxsize=500,
filegrowth=1),
FILEGROUP [Data Test DB FG2]
(name='Data Test DB FG2',
filename='d:\DataDB\FG2\Data Test DB FG2.ndf',
size=5,
maxsize=500,
filegrowth=1),
FILEGROUP [Data Test DB FG3]
(name='Data Test DB FG3',
filename='d:\DataDB\FG3\Data Test DB FG3.ndf',
size=5,
maxsize=500,
filegrowth=1),
FILEGROUP [Data Test DB FG4]
(name='Data Test DB FG4',
filename='d:\DataDB\FG4\Data Test DB FG4.ndf',
size=5,
maxsize=500,
filegrowth=1)


-------------------------------------------------------
--接下来,我们创建分区表函数,这其实可以理解为一个规则,说明如何以一个规则来将一个表来划分,如下

use TestDB
go
create partition function DataPartionRange(int)
as range left for values(100,200,300)
--其中分区函数的名称是Data Partition Range,后面的类型(int)表明接下来用来分区的那个字段的类型是INT类型,而VALUES (100,200,300)表明,将把表分为4个区了,是从负数到100,100-200,200-300,大于300。

 

--接下来,我们要创建分区架构,即将分区函数应用到我们分好的四个文件组里面去

use TestDB
go
create partition scheme DataPartitionScheme
as partition DataPartionRange
to([Data Test DB FG1],[Data Test DB FG2],[Data Test DB FG3],[Data Test DB FG4]);

---创建表试试
use TestDB
go
create table MyTable
(
ID int not Null,
Date datetime,
Cost money
)on DataPartitionScheme(ID);

--填充表
USE TestDB
go
declare @count int
set @count =-25
while @count <=100
begin
insert into MyTable select @count,getdate(),100.00
set @count=@count+1
end
set @count =101
while @count <=200
begin
insert into MyTable select @count,getdate(),200.00
set @count=@count+1
end
set @count =201
while @count <=300
begin
insert into MyTable select @count,getdate(),300.00
set @count=@count+1
end
set @count =301
while @count <=400
begin
insert into MyTable select @count,getdate(),400.00
set @count=@count+1
end
set @count =401
while @count <=800
begin
insert into MyTable select @count,getdate(),500.00
set @count=@count+1
end

--最后,我们可以查询下,插入的这些数据,是否真的被划分到四个不同的文件组里的表分区了,可以这样看
SELECT *,$PARTITION.DataPartionRange(ID)
FROM MyTable
--where $PARTITION.DataPartionRange(ID)=4

 

 

分区的维护主要设计分区的添加、减少、合并和在分区间转换。可以通过ALTER PARTITION FUNCTION的选项SPLITMERGEALTER TABLE的选项SWITCH来实现。SPLIT会多增加一个分区,而MEGRE会合并或者减少分区,SWITCH则是逻辑地在组间转换分区。

 

 

 

你可能感兴趣的:(SQL Server)