0

我正在创建一个查询,它将选择“x”个条目的随机列表。我希望能够更改每次运行查询时查询返回的值的数量。

是否可以提示 TOP 返回值,而不必每次都打开查询设计?

SELECT TOP 50 *
FROM [MyTableName]
ORDER BY Rnd([SomeNumber]);
4

1 回答 1

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
于 2013-03-10T14:33:07.513 回答