数据库分区

摘自http://www.cnblogs.com/jianjialin/archive/2012/11/30/2796608.html

数据表分区, 全新分区

设计好了分区方案才新建数据表的话

1.使用向导或者脚本新建数据库如下

image

2. 新建分区函数, 再建分区方案, 并制定这个分区函数

create partition function pt_orderdate(datetime)
as range right
for values('2003/01/01','2004/01/01')
go
 
create partition scheme PS_OrderDate
as partition PT_OrderDate to (SaleFile1,SaleFile3,SaleFile3)
GO

3.  新建数据表和插入测试数据

IF exists (select 1 from sysobjects where id=object_id('Orders') and type='U')
    drop table Orders
create table Orders(
    OrderID int identity(10000,1),
    OrderDate datetime not null,
    CustomerID int not null,
    constraint pk_orders primary key (orderid, orderdate)
) on ps_orderDate(orderdate)
 
IF exists (select 1 from sysobjects where id=object_id('OrdersHistory') and type='U')
    drop table OrdersHistory
create table OrdersHistory(
    OrderID int identity(10000,1),
    OrderDate datetime not null,
    CustomerID int not null,
    constraint pk_OrdersHistory primary key (orderid, orderdate)
) on ps_orderDate(orderdate)
 
go
 
insert into Orders(OrderDate,CustomerID) values
('2002/06/25',1000),('2002/08/13',1000),('2002/8/25',1000),('2002/9/23',1000),
('2003/06/25',1000),('2003/08/13',1000),('2003/8/25',1000),('2003/9/23',1000)

4. 查看

运行select *,$partition.pt_orderdate(OrderDate) partitionID from Orders

得到image 2003年的记录在第二个分区.

select $partition.pt_orderdate(orderdate) as partition, COUNT(*) as countNum from dbo.Orders
        group by $partition.pt_orderdate(OrderDate)
        order by partition

得到image每个分区的数据条数.

5. 归档.  假如是年初, 我们吧2002年的数据都归档到历史订单表OrdersHistory中.

use PT_Sales
go

alter table orders switch partition 1 to ordershistory partition 1
go

这句话, 把Orders表分区1里面的记录归档到了 OrdersHistory的分区一里面去了.  那么Orders的表的记录是不是只有2003年的四条了呢

然后查询select * from ordersimage果然是这样的.   image

6. 添加分区

/*
添加分区
*/
use PT_Sales
go
/*指定新分区的数据存储在哪个文件. 
--这里 next userd SaleFile3 表示我们将新分区的数据保存在SaleFile3文件组中.
--当然我们也可以新建一个文件组SaleFile4, 这里我们直接使用2了. */
alter partition scheme ps_OrderDate next used SaleFile3
/*--表示我们创建一个新的分区数据, split range(20050101)是分区的关键点.*/
alter partition function pt_orderdate() split range('2005/01/01')
 
 

现在我们已经添加了分区4(不过这个分区4是在SaleFile3上. 2005年之后的数据将保存到分区四中.)

insert into Orders(OrderDate,CustomerID) values
('2006/06/25',1000),('2006/08/13',1000),('2006/8/25',1000),('2006/9/23',1000),
('2007/06/25',1000),('2007/08/13',1000),('2007/8/25',1000),('2007/9/23',1000)
image得到了如图. 
 
7.  删除分区
use PT_Sales
go
 
alter partition function pt_orderdate() merge range('2005/01/01')
go
 
select *,$partition.pt_orderdate(orderdate) from orders
 
 
select * from sys.partition_functions
select * from sys.partition_range_values
select * from sys.partition_schemes
 

image

看, 第一个 分区函数, fanout扇区只有两个了. 分区的标识 只有一个了 2004/01/01, 还有分区架构.

原文地址:https://www.cnblogs.com/nygfcn1234/p/3110089.html