且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 SQL Server 表中选择 n 个随机行

更新时间:2023-02-03 14:25:56

select top 10 percent * from [yourtable] order by newid()

针对有关大型表的纯垃圾"评论:您可以这样做以提高性能.

In response to the "pure trash" comment concerning large tables: you could do it like this to improve performance.

select  * from [yourtable] where [yourPk] in 
(select top 10 percent [yourPk] from [yourtable] order by newid())

这样做的成本将是值的键扫描加上连接成本,这在具有小百分比选择的大表上应该是合理的.

The cost of this will be the key scan of values plus the join cost, which on a large table with a small percentage selection should be reasonable.