首页 > 解决方案 > 基于不在主键中的列对 SQL Server 表进行分区?

问题描述

假设我有一张这样的桌子:

create table test_partitions 
(
    pk_id int not null,
    col1 nvarchar(20),
    col2 nvarchar(100),

    constraint pk_test_partitions primary key (pk_id, col1)
);

我想对该表进行分区以提高查询性能,这样我就不必每次需要时都查看整个表。所以我添加了一个计算列:

create table test_partitions 
(
    pk_id int not null,
    partition_id as pk_id % 10 persisted not null,
    col1 nvarchar(20),
    col2 nvarchar(100),

    constraint pk_test_partitions primary key (pk_id, col1)
);

所以每当我这样做时,我都select * from test_partitions where pk_id = 123希望 SQL Server 只查看整个表的 1/10。我不想将partition_id列添加到主键,因为它永远不会成为 where 子句的一部分。如何对我的表进行分区partition_id

标签: sql-server

解决方案


为了提高查询性能,您可以应用分页。也就是说,您可以使用fetch next query 来实现您的输出。请通过了解更多详细信息。

  SELECT column-names FROM table-name
  ORDER BY column-names 
  OFFSET n ROWS
  FETCH NEXT m ROWS ONLY

推荐阅读