我正在创建一个查询,它将选择一个'x'个条目的随机列表。我希望能够在每次运行查询时更改查询返回的值的数量。
是否可以提示输入TOP返回值而不必每次都打开查询设计?
SELECT TOP 50 *
FROM [MyTableName]
ORDER BY Rnd([SomeNumber]);
答案 0 :(得分:1)
不幸的是,这似乎是最明显的方法,即......
PARAMETERS RowsToReturn Long;
SELECT TOP [RowsToReturn] *
FROM MyTableName
ORDER BY Rnd([SomeNumber]);
......不行。 Access抱怨SQL查询无效。
我接近它的方法是创建一个像下面这样的小VBA函数,然后创建一个使用RunCode
动作来调用它的宏
Public Function buildRandomTopN()
'
' assumes that the table has an AutoNumber primary key named [ID]
'
Dim rowsToReturn As Long, cdb As DAO.Database, qdf As DAO.QueryDef
Const queryName = "randomTopN" ' existing QueryDef to update
On Error Resume Next
rowsToReturn = CLng(InputBox("Number of rows to return"))
If Err.Number = 0 Then
On Error GoTo 0
If rowsToReturn > 0 Then
Set cdb = CurrentDb
' update the SQL statement for the query
Set qdf = cdb.QueryDefs(queryName)
qdf.SQL = "SELECT TOP " & rowsToReturn & " * FROM [MyTableName] " & _
"ORDER BY Rnd([ID])"
qdf.Close
Set qdf = Nothing
Set cdb = Nothing
' open the query
DoCmd.OpenQuery queryName
End If
End If
End Function