sql-server - TABLESAMPLE 返回错误的行数?

标签 sql-server tsql sql-server-2005

我刚刚发现了 TABLESAMPLE子句,但令人惊讶的是它没有返回我指定的行数。

我使用的表有大约 14M 行,我想要 10000 行的任意样本。

select * from tabData TABLESAMPLE(10000 ROWS)

每次执行时我得到的不是 10000,而是不同的数字(8000 到 14000 之间)。

这是怎么回事,我是否误解了TABLESAMPLE的预期目的?

编辑:

David's link解释得很好。

这总是以有效的方式返回 10000 个大致随机的行:

select TOP 10000 * from tabData TABLESAMPLE(20000 ROWS);

REPEATABLE选项有助于获得始终相同的结果(除非数据已更改)

select TOP 10000 * from tabData TABLESAMPLE(10000 ROWS) REPEATABLE(100);

因为我想知道使用带有大量行的TABLESAMPLE是否更昂贵以确保(?)我获得正确的行号,所以我已经测量了它;

1.循环(20次):

select TOP 10000 * from tabData TABLESAMPLE(10000 ROWS);

(9938 row(s) affected)
(10000 row(s) affected)
(9383 row(s) affected)
(9526 row(s) affected)
(10000 row(s) affected)
(9545 row(s) affected)
(9560 row(s) affected)
(9673 row(s) affected)
(9608 row(s) affected)
(9476 row(s) affected)
(9766 row(s) affected)
(10000 row(s) affected)
(9500 row(s) affected)
(9941 row(s) affected)
(9769 row(s) affected)
(9547 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(9478 row(s) affected)
First batch(only 10000 rows) completed in: 14 seconds!

2.循环(20次):

select TOP 10000 * from tabData TABLESAMPLE(10000000 ROWS);

(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
Second batch(max rows) completed in: 13 seconds!

3.loop:使用 ORDER BY NEWID() 对 100% 随机行进行计数器检查:

select TOP 10000 * from tabData ORDER BY NEWID();

(10000 row(s) affected)

在持续23分钟的一次执行后被取消

结论:

因此,令人惊讶的是,使用精确的 TOP 子句和 TABLESAMPLE 中的大量数字的方法并不慢。因此,如果行不是每行随机而是每页级别(表的每个 8K 页都被赋予一个随机值)并不重要,那么它是 ORDER BY NEWID() 的一个非常有效的替代方案.

最佳答案

请参阅article here 。您需要添加顶部子句和/或使用可重复选项来获取所需的行数。

关于sql-server - TABLESAMPLE 返回错误的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10725839/

相关文章:

c# - SQL Server 登录在应用程序运行过程中失败

sql - 对相同日期和 ID 的列中的值求和

mysql - 将现有 MsSQL 数据库迁移到 MySql 的最佳方法?

sql - 选择结果作为用户定义的表参数函数中的参数

sql-server - 是否有任何工具可以在 Microsoft SQL Server (MSSQL) 上进行迁移(la Ruby)?

SQL Server 相当于 MySQL 枚举数据类型?

sql - varchar(500) 比 varchar(8000) 有优势吗?

sql - 将JDE朱利安日期转换为公历

sql-server-2005 - 如何将行转置为列?

sql - 可选参数, "index seek"计划