sql server 2005中的表分区

来源:互联网 发布:宁波每日新房成交数据 编辑:程序博客网 时间:2024/05/28 23:10

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]GOCREATE 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]GOCREATE 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]goCREATE 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]godeclare @count intset @count =-25while @count <=100begininsert into MyTable select @count,getdate(),100.00set @count=@count+1endset @count =101while @count <=200begininsert into MyTable select @count,getdate(),200.00set @count=@count+1endset @count =201while @count <=300begininsert into MyTable select @count,getdate(),300.00set @count=@count+1endset @count =301while @count <=400begininsert into MyTable select @count,getdate(),400.00set @count=@count+1endset @count =401while @count <=800begininsert into MyTable select @count,getdate(),500.00set @count=@count+1end


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

原创粉丝点击