Solved

Access - most efficient way to locate records

Posted on 2013-05-28
5
426 Views
Last Modified: 2013-05-28
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?
0
Comment
Question by:terpsichore
  • 3
  • 2
5 Comments
 
LVL 57
ID: 39201502
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
 
LVL 57
ID: 39201512
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
 

Author Comment

by:terpsichore
ID: 39201525
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
 
LVL 57

Accepted Solution

by:
Jim Dettman (Microsoft MVP/ EE MVE) earned 500 total points
ID: 39201562
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
 

Author Closing Comment

by:terpsichore
ID: 39201678
very thorough, thoughtful response
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Most if not all databases provide tools to filter data; even simple mail-merge programs might offer basic filtering capabilities. This is so important that, although Access has many built-in features to help the user in this task, developers often n…
Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
In Microsoft Access, learn how to “cascade” or have the displayed data of one combo control depend upon what’s entered in another. Base the dependent combo on a query for its row source: Add a reference to the first combo on the form as criteria i…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now