--
创建数据库即文件组
create
database
dbStudy
on
primary
(name
=
'
dbPrimary
'
,
filename
=
'
d:\dbprimary.mdf
'
),
filegroup dbstudyfilegroup1
(name
=
'
dbgroupfile1
'
,
filename
=
'
d:\dbgroupfile1.ndf
'
),
(name
=
'
dbgroupfile2
'
,
filename
=
'
d:\dbgroupfile2.ndf
'
),
filegroup dbstudyfilegroup2
(name
=
'
dbgroupfile3
'
,
filename
=
'
d:\dbgroupfile3.ndf
'
),
filegroup dbstudyfilegroup3
(name
=
'
dbgroupfile4
'
,
filename
=
'
d:\dbgroupfile4.ndf
'
)
log
on
(name
=
'
dbstudylog
'
,
filename
=
'
d:\dbgrouplog.ldf
'
)
go
--
创建分区函数,指定类型为datetime,因为有四个文件,所以这里
--
定义三个分区点
create
partition
function
fn_partition (
datetime
)
as
RANGE
RIGHT
FOR
VALUES
(
'
20000401
'
,
'
20000701
'
,
'
20001001
'
)
--
创建分区架构,使文件组与函数相关联
create
partition scheme Scheme_orderDate
as
partition fn_partition
to
(
[
PRIMARY
]
,
[
dbstudyfilegroup1
]
,
[
dbstudyfilegroup2
]
,
[
dbstudyfilegroup3
]
)
--
-开始对表分区
CREATE
TABLE
[
dbo
]
.
[
Orders
]
(
[
orderid
]
[
int
]
NOT
NULL
,
[
orderdate
]
datetime
NOT
NULL
,
[
empid
]
[
int
]
NOT
NULL
,
[
custid
]
[
varchar
]
(
5
)
NOT
NULL
,
[
qty
]
[
int
]
NOT
NULL
)
ON
Scheme_orderDate(
[
orderdate
]
)
--
添加测试数据
insert
into
orders
values
(
1
,
'
20000301
'
,
1
,
1
,
1
)
insert
into
orders
values
(
1
,
'
20000301 12:12:2
'
,
1
,
1
,
1
)
insert
into
orders
values
(
1
,
'
20000401
'
,
1
,
1
,
1
)
insert
into
orders
values
(
2
,
'
20000701
'
,
1
,
1
,
1
)
insert
into
orders
values
(
3
,
'
20001001
'
,
1
,
1
,
1
)
insert
into
orders
values
(
4
,
'
20000402
'
,
1
,
1
,
1
)
insert
into
orders
values
(
5
,
'
20000705
'
,
1
,
1
,
1
)
insert
into
orders
values
(
6
,
'
20001004
'
,
1
,
1
,
1
)
--
数据查询
select
partition
=
$partition.fn_partition(OrderDate)
,rows
=
count
(
*
)
,minval
=
min
(OrderDate)
,maxval
=
max
(OrderDate)
from
dbo.Orders
group
by
$partition.fn_partition(OrderDate)
order
by
partition
--
创建分区聚集索引
create
clustered
index
ClusterOrderId
on
orders(orderid)
drop
index
orders.clusterorderid
--
为分区表设置主键
--
必须把分区列包含在主键/唯一约束/唯一索引的键列中
alter
table
dbo.Orders
add
constraint
PK_Orders
primary
key
(OrderID,OrderDate)
go