将表切成大小为N的树干?

时间:2015-10-28 23:01:41

标签: sql-server sql-server-2012

我想写一个存储过程

create proc GetTrunk @trunk int, @tableName sysname, @trunksize int = 5000
as
with    t as ( 
           select PK1, PK2, ntile(@trunksize) over ( order by PK1, PK2 ) t
           from     ABigTable -- Just put table name directly here for testing
 -- the table has a composite pk of pk1 and pk2
         )
select  pk1, pk2
from    t
where   t = @trunk;

运行GetTrunk 3, 'tname', 5000会将表格切换为大小为5000的中继,并获取中继的第3主干密钥。

但是,对于大桌子来说这很慢。这是获得桌面窗口的更好方法吗?

1 个答案:

答案 0 :(得分:0)

您可以试用ORDER BY enhancements of OFFSET and FETCH。像这样:

create proc GetTrunk @trunk int, @tableName sysname, @trunksize int = 5000
as

           select PK1, PK2
           from     ABigTable 
           order by PK1, PK2 OFFSET ((@trunk -1) * @trunksize)  ROWS 
    FETCH NEXT @trunksize ROWS ONLY 

我认为它的表现会比NTILE好。