数据库分区是一种物理数据库设计技术,DBA和数据库建模人员对其相当熟悉。虽然分区技术可以实现很多效果,但其主要目的是为了在特定的SQL操作中减少数据读写的总量以缩减响应时间。
分类
1、水平分区(Horizontal Partitioning)
这种形式分区是对表的行进行分区,通过这样的方式不同分组里面的物理列分割的数据集得以组合,从而进行个体分割(单分区)或集体分割(1个或多个分区)。所有在表中定义的列在每个数据集中都能找到,所以表的特性依然得以保持。
2、垂直分区(Vertical Partitioning)
这种分区方式一般来说是通过对表的垂直划分来减少目标表的宽度,使某些特定的列被划分到特定的分区,每个分区都包含了其中的列所对应的行
创建分区函数
--创建分区函数
create partition function cat_test(int)
as range left
for values('10','20')
--查看分区函数
select * from sys.partition_functions
create partition scheme cat_test_scheme
as partition cat_test
to(fg01,fg02,fg03)
--查看分区方案
select * from sys.partition_schemes
--创建分区表
create table cat_test
(
id int not null,
name varchar(20) null
) on cat_test_scheme(id)
insert into cat_test
select 1,'jk'
union all
select 6,'mk'
union all
select 11,'pk'
union all
select 20,'ik'
union all
select 2,'kk'
union all
select 5,'jm'
union all
select 12,'jk'
union all
select 15,'jk'
union all
select 30,'jkw'
select * from cat_test
-- 查询每个分区的数据
select * from cat_test
where $partition.cat_test(id)=1
--查询分区列在那个分区
select $partition.cat_test(30)
--查询每个分区有多少数据
select $partition.cat_test(id) as id,
count(1)
from cat_test
group by $partition.cat_test(id)
---修改分区方案
alter partition scheme cat_test_scheme
next used fg04
---修改分区函数
alter partition function cat_test()
split range ('5')
---删除分区
alter partition function cat_test()
merge range('5')
**---使用switch移动数据到普通表**
-- create table
create table ST_cat
(id int not null,
name varchar(20)
)on cat_test_scheme(id)
--- switch table
alter table cat_test switch partition 4 to ST_cat partition 4
select *from ST_cat
--把分区表的数据移动到普通表
create table ST_cat_P
(id int not null,
name varchar(20)
)on fg03
--drop table ST_cat_P
alter table ST_cat
switch partition 4 to ST_cat_P
select * from ST_cat_P
---普通表转分区表
--1、 在分区表上创建聚集索引,在对索引分区
create clustered index ix_id
on [dbo].[ST_cat_P](ID)
on cat_test_scheme(id)
--2、复制到新的分区表
**--把分区表转换普通表**
--1、删除分布区边界值
alter partition function cat_test()
merge range('20')
--2、删除分区索引并重建索引在文件组上
drop index [ST_cat_P].ix_id
create clustered index ix_id
on [dbo].[ST_cat_P](ID)
on [primary]
drop index ix_id on [ST_cat_P]