Access - most efficient way to locate records

I am writing a number of functions to check certain conditions in one of my tables and am looking for the most efficient way.

I have a 'milestone' table, which is related to 2 other key tables. I need to basically look to see if certain records either exist or meet certain conditions.

Is the following a good way to go about it?

1)      I created a new Query containing all the key fields: project_ID, Part_ID, RevenueID, etc.
2)      In the relevant function, I was thinking of creating a DAO recordset, and then using a select statement with the relevant subset/in the right order:
Set rstFrom = CurrentDb.OpenRecordset("SELECT * FROM … WHERE... ORDER BY …")
3)      I can then use findfirst or scan through the records to test for certain conditions.

Is that the best way to go about it?
terpsichoreAsked:
Who is Participating?
 
Jim Dettman (Microsoft MVP/ EE MVE)Connect With a Mentor PresidentCommented:
Take a look at the following code, which uses seek to see if a key already exists in a table.  The one trick (and the reason a lot of folks don't use seek) is that if it is a linked table, you must first open the remote database in code (Set dbRemote = wrk.OpenDatabase(strPath, False, True)).

 Depending on the needs of the app, I would open it at form startup or at the start of the app and then close appropriately.   You really would not want to open/close repeatedly if it was an intensive process.

Jim.

'
' Get a unique record key.
'
Function GetRecordKey(strTableName As String, strKeyParam As String) As Variant

  Const Routine = "GetRecordKey"
  Const Version = "1.0"
 
  Dim wrk As Workspace
  Dim dbCurrent As Database
  Dim dbRemote As Database
  Dim tdfAttached As TableDef
  Dim strPath As String
  Dim rst1 As Recordset
  Dim rst2 As Recordset
  Dim intlKeyValue As Long
  Dim lngWait As Long
  Dim lngX As Long
  Dim intLockCount As Integer
 
  GetRecordKey = Null

  On Error GoTo GetRecordKeyError

  Set dbCurrent = CurrentDb()

'
' First, get the key type.
'
  Set rst1 = dbCurrent.OpenRecordset("qrysysTableKeys", dbOpenDynaset)
  rst1.FindFirst "[TableName]= '" & strTableName & "'"
 
  If rst1.NoMatch Then
    ' Not good.  Need an entry for the table to generate a key.
    gstrMBTitle = "Generate key error"
    gstrMBMsg = "Can't generate key.  No entry in key table"
    gintMBDef = MB_OK + MB_ICONSTOP
    gintMBBeep = True
    gintMBLog = True
    Call DisplayMsgBox
    GoTo GetRecordKeyExit
  End If

'
' Now Generate a key based on the key type
'
GetAKey:
    Select Case rst1![KeyType]
   
    Case 1
    ' Key is simple numeric counter (ie xxxxxxx).
      rst1.Edit
      intlKeyValue = CLng(rst1![LastKeyValue]) + 1
      If intlKeyValue > rst1![MaximumValue] Then intlKeyValue = 1
      rst1![LastKeyValue] = Format$(intlKeyValue)
      rst1.Update
      GetRecordKey = intlKeyValue

    'Case 2
    ' Key is a base + a numeric counter (ie.  ABAxxx)
     

    Case Else
      ' Undefined key type
      gstrMBTitle = "Undefined call"
      gstrMBMsg = "Can't generate key.  Invalid key type."
      gintMBDef = MB_OK + MB_ICONSTOP
      gintMBBeep = True
      gintMBLog = True
      Call DisplayMsgBox
      GoTo GetRecordKeyExit
    End Select

    '
    ' Got a key.  Does it need to be tested for unique?
    '
    If (rst1![UniqueKey]) Then
        If dbRemote Is Nothing Then
            Set wrk = DBEngine.Workspaces(0)
            Set dbCurrent = wrk.Databases(0)
            Set tdfAttached = dbCurrent.TableDefs(strTableName)
            strPath = tdfAttached.Connect
            strPath = right$(strPath, Len(strPath) - InStr(strPath, "="))
            Set dbRemote = wrk.OpenDatabase(strPath, False, True)
        End If
       
        Set rst2 = dbRemote.OpenRecordset(strTableName, DB_OPEN_TABLE)
        rst2.index = "PrimaryKey"
        rst2.Seek "=", intlKeyValue
        If Not (rst2.NoMatch) Then
            rst2.Close
            GoTo GetAKey
        Else
            rst2.Close
        End If
    End If
     
GetRecordKeyExit:
    Set dbCurrent = Nothing
   
    If Not rst1 Is Nothing Then
      rst1.Close
      Set rst1 = Nothing
    End If
   
    If Not rst1 Is Nothing Then
      rst2.Close
      Set rst2 = Nothing
    End If
   
    If Not dbRemote Is Nothing Then
      dbRemote.Close
      Set dbRemote = Nothing
    End If
   
    Exit Function

GetRecordKeyError:
  'Table locked by another user
    If Err = CNT_ERR_RESERVED Or Err = CNT_ERR_COULDNT_UPDATE Or Err = CNT_ERR_OTHER Then
        intLockCount = intLockCount + 1
        If intLockCount > 5 Then
            GetRecordKey = Null
            Resume GetRecordKeyExit
        Else
            DoEvents
            DBEngine.Idle DB_FREELOCKS
            lngWait = intLockCount ^ 2 * Int(Rnd * 20 + 5)
            For lngX = 1 To lngWait
                DoEvents
            Next lngX
            Resume
        End If
    Else
      UnexpectedError ModuleName, Routine, Version, Err, Error$
      GetRecordKey = Null
      Resume GetRecordKeyExit
    End If

End Function
0
 
Jim Dettman (Microsoft MVP/ EE MVE)PresidentCommented:
If your simply checking for existence, you can use a DCount() or open a recordset with:

SELECT COUNT(*) FROM < >  WHERE < >

If you really want some speed, the fastest way is to open a recordset as a table type, set an index, and use the Seek method on the index.  This by far is the fastest way to search for a record.

Jim.
0
 
Jim Dettman (Microsoft MVP/ EE MVE)PresidentCommented:
Note:  I made the assumption that your using an Access database to store the data.

If not, or you think you'll move to SQL or something else in the future, then stick to DCount("*","table","where") or the SELECT COUNT(*) syntax.

Jim.
0
 
terpsichoreAuthor Commented:
can you give an example (pseudo code) using seek where, for example, I am trying to see if there is a record that meets various criteria, including being part of a given project or part (key fields in related table)?
thank you.
0
 
terpsichoreAuthor Commented:
very thorough, thoughtful response
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.