Solved

Access - most efficient way to locate records

Posted on 2013-05-28
5
469 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 58
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 58
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 58

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

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As tax season makes its return, so does the increase in cyber crime and tax refund phishing that comes with it
Traditionally, the method to display pictures in Access forms and reports is to first download them from URLs to a folder, record the path in a table and then let the form or report pull the pictures from that folder. But why not let Windows retr…
Familiarize people with the process of utilizing SQL Server views from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Access…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.

696 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