如何从我们总共拥有的一组X记录中检索N个随机记录。例如,如果我们在我们的网站上有一个包含2000个链接到不同页面的表,我们如何检索10个随机记录?
答案 0 :(得分:2)
SELECT TOP 10 *
FROM tableName
ORDER BY NEWID()
答案 1 :(得分:1)
尝试像这样使用动态SQL。请注意,由于某些边缘情况未被覆盖,例如COUNT()返回0或记录计数大于COUNT()等情况,因此需要更多工作。
CREATE PROCEDURE dbo.RandomNRecords
(
@recordCount int
)
as
begin
declare @counter int
declare @sqlQuery nvarchar(2000)
SET @sqlQuery = '
CREATE TABLE #TempTable
(
f1 varchar(50),
f2 varchar(50),
f3 int,
id int identity(1,1)
)
INSERT INTO #TempTable
SELECT f1, f2, f3 FROM Table1
SELECT *
FROM #TempTable
WHERE id in ('
SELECT @recordCount = COUNT(*) From Table1
SET @counter = 0
WHILE @counter < @recordCount
BEGIN
SET @counter = @counter + 1
SET @sqlQuery = @sqlQuery + CONVERT(varchar,Round((@recordCount * Rand()), 0)) + ','
END;
SET @sqlQuery = SUBSTRING(@sqlQuery, 1, LEN(sqlQuery) - 1) --remove last comma
SET @sqlQuery = @sqlQuery + ')'
EXEC sp_executesql @sqlQuery
END
答案 2 :(得分:0)
declare @numberOfRecordsToGet int = 5
select top (@numberOfRecordsToGet) * from name_of_your_tbl order by newid()
答案 3 :(得分:0)
在商店程序中使用它
声明@N varchar(10)
设置@ N = '10'
exec('SELECT TOP'+ @ N +'* FROM tableName ORDER BY NEWID()')