A. 要得到隨機排序的列,或者返回x條隨機選擇的列,你可以使用隨機數。但是RAND函數在一個查詢中只能返回一個結果。你可以在NOWID函數返回的列上做ORDER BY。請看示例:
SELECT *
FROM Northwind..Orders
ORDER BY NEWID()
SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()
這段話翻譯得真是費勁,干脆不管原文,直接意譯了。
不過提醒大家注意,這種方法是要對整個表掃描,然後產生一個計算列再排序的,最好不要對大的表作這樣的操作,否則會很慢的。
Q. How can I randomly sort query results?
A. To randomly order rows, or to return x number of randomly chosen rows, you can use the RAND function inside the SELECT statement. But the RAND function is resolved only once for the entire query, so every row will get same value. You can use an ORDER BY clause to sort the rows by the result from the NEWID function, as the following code shows:
SELECT *
FROM Northwind..Orders
ORDER BY NEWID()
SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()
—SQL Server MVPs