在访问中生成随机数后如何解决随机数?

时间:2019-05-13 21:39:38

标签: ms-access

我为每行生成了唯一的伪随机数,这些伪随机数受Access中查询中特定字段(Field1)的约束。它们已经成功生成,我想修复它们(有点像复制和粘贴作为值)。我想我的问题是,这是执行此操作的最佳方法,还是在查询中重新计算它们时总会改变?我对其他建议持开放态度,但是,一旦对它们进行了首次计算,我希望它们保持原样并且不再更改。谢谢!

这是当前查询的SQL:

.mw-120

1 个答案:

答案 0 :(得分:1)

您不需要桌子。您可以使用集合:

' Builds random row numbers in a select, append, or create query
' with the option of a initial automatic reset.
'
' Usage (typical select query with random ordering):
'   SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
'   FROM SomeTable
'   WHERE (RandomRowNumber(CStr([ID])) <> RandomRowNumber("",True))
'   ORDER BY RandomRowNumber(CStr([ID]));
'
' The Where statement shuffles the sequence when the query is run.
'
' Usage (typical select query for a form with random ordering):
'   SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
'   FROM SomeTable
'   ORDER BY RandomRowNumber(CStr([ID]));
'
' The RandomRowID values will resist reordering and refiltering of the form.
' The sequence can be shuffled at will from, for example, a button click:
'
'   Private Sub ResetRandomButton_Click()
'       RandomRowNumber vbNullString, True
'       Me.Requery
'   End Sub
'
' and erased each time the form is closed:
'
'   Private Sub Form_Close()
'       RandomRowNumber vbNullString, True
'   End Sub
'
' Usage (typical append query, manual reset):
' 1. Reset random counter manually:
'   Call RandomRowNumber(vbNullString, True)
' 2. Run query:
'   INSERT INTO TempTable ( [RandomRowID] )
'   SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
'   FROM SomeTable;
'
' Usage (typical append query, automatic reset):
'   INSERT INTO TempTable ( [RandomRowID] )
'   SELECT RandomRowNumber(CStr([ID])) AS RandomRowID, *
'   FROM SomeTable
'   WHERE (RandomRowNumber("",True)=0);
'
' 2018-09-11. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RandomRowNumber( _
    ByVal Key As String, _
    Optional Reset As Boolean) _
    As Single

    ' Error codes.
    ' This key is already associated with an element of this collection.
    Const KeyIsInUse        As Long = 457

    Static Keys             As New Collection

    On Error GoTo Err_RandomRowNumber

    If Reset = True Then
        Set Keys = Nothing
    Else
        Keys.Add Rnd(-Timer * Keys.Count), Key
    End If

    RandomRowNumber = Keys(Key)

Exit_RandomRowNumber:
    Exit Function

Err_RandomRowNumber:
    Select Case Err
        Case KeyIsInUse
            ' Key is present.
            Resume Next
        Case Else
            ' Some other error.
            Resume Exit_RandomRowNumber
    End Select

End Function

我的文章Random Rows in Microsoft Access

中对此进行了详细说明。

(如果没有帐户,请浏览链接:阅读全文)。

包含演示的完整代码位于GitHub:VBA.RowNumbers