sql server 2005中的表分区

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

比如,在C盘下建立如下几个目录
C:\Data2\Primary
C:\Data2\FG1
C:\Data2\FG2
C:\Data2\FG3
C:\Data2\FG4

其中primary存放的是主数据库文件,其他FG1--FG4存放四个单独的文件组,可以见创立数据库
Data Partition DB2,如下
USE [master]

GO

/****** Object:  Database [Data Partition DB]    Script Date: 10/08/2006 23:09:53 ******/

IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'Data Partition DB2')

DROP DATABASE [Data Partition DB2]

GO

CREATE DATABASE [Data Partition DB2]

ON PRIMARY

(NAME='Data Partition DB Primary FG',

FILENAME=

'C:\Data2\Primary\Data Partition DB Primary FG.mdf',

SIZE=5,

MAXSIZE=500,

FILEGROWTH=1 ),

FILEGROUP [Data Partition DB FG1]

(NAME = 'Data Partition DB FG1',

FILENAME =

'C:\Data2\FG1\Data Partition DB FG1.ndf',

SIZE = 5MB,

MAXSIZE=500,

FILEGROWTH=1 ),

FILEGROUP [Data Partition DB FG2]

(NAME = 'Data Partition DB FG2',

FILENAME =

'C:\Data2\FG2\Data Partition DB FG2.ndf',

SIZE = 5MB,

MAXSIZE=500,

FILEGROWTH=1 ),

FILEGROUP [Data Partition DB FG3]

(NAME = 'Data Partition DB FG3',

FILENAME =

'C:\Data2\FG3\Data Partition DB FG3.ndf',

SIZE = 5MB,

MAXSIZE=500,

FILEGROWTH=1 ),

FILEGROUP [Data Partition DB FG4]

(NAME = 'Data Partition DB FG4',

FILENAME =

'C:\Data2\FG4\Data Partition DB FG4.ndf',

SIZE = 5MB,

MAXSIZE=500,

FILEGROWTH=1 )

接下来,我们创建分区表函数,这其实可以理解为一个规则,说明如何以一个规则来将一个表来划分,如下
use [Data Partition DB2] GO CREATE PARTITION FUNCTION [Data Partition Range](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 [Data Partition DB2]

go

CREATE PARTITION SCHEME [Data Partition Scheme]

AS PARTITION [Data Partition Range]

TO ([Data Partition DB FG1], [Data Partition DB FG2], [Data Partition DB FG3],[Data Partition DB FG4]);
 
再创建表的结构
USE [Data Partition DB2]

go
CREATE TABLE MyTable
(ID INT NOT NULL, Date DATETIME, Cost money)    
   ON [Data Partition Scheme] (ID);

这里注意,ON [Data Partition Scheme] (ID);表明,划分时以ID的大小作为划分的根据,ON后要跟分区架购的名称

最后,我们可以填充数据了

USE [Data Partition DB2]

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.[Data Partition Range](ID)
 FROM MyTable

你可能感兴趣的:(sql server 2005)