473,411 Members | 2,078 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,411 software developers and data experts.

dcount or DAO.recordset?

99 64KB
In MS Access VBA, I want to see whether a record exist or not. During googling, two suggestions were found. One is using DAO and the other is using dcount or dlookup. Is there any suggestion which one is the best option please?
Regards
Jun 18 '16 #1
4 3536
PhilOfWalton
1,430 Expert 1GB
IMO the recordset approach is faster, because it uses indexes ... but for for a few Dlookups you won't notice any difference. If you are looping a number of DLookups in linked tables, you might spot a difference.
One advantage of a DLookup is that if you have a query that is not updateable, you can often get over the problem by removing the table that is causing the poblem and using a DLookup instead.

Out of interest, I attach some code written by Allen Brown, which simulated DLookup, bur appears faster.

Expand|Select|Wrap|Line Numbers
  1. Public Function ELookup(Expr As String, Domain As String, Optional Criteria As Variant, _
  2.     Optional ORDERClause As Variant) As Variant
  3.  
  4.     On Error GoTo Err_ELookup
  5.     'Purpose:   Faster and more flexible replacement for DLookup()
  6.     'Arguments: Same as DLookup, with additional Order By option.
  7.     'Return:    Value of the Expr if found, else Null.
  8.     '           Delimited list for multi-value field.
  9.     'Author:    Allen Browne. allen@allenbrowne.com
  10.     'Updated:   December 2006, to handle multi-value fields (Access 2007.)
  11.     'Examples:
  12.     '           1. To find the last value, include DESC in the OrderClause, e.g.:
  13.     '               ELookup("[Surname] & [FirstName]", "tblClient", , "ClientID DESC")
  14.     '           2. To find the lowest non-null value of a field, use the Criteria, e.g.:
  15.     '               ELookup("ClientID", "tblClient", "Surname Is Not Null" , "Surname")
  16.     'Note:      Requires a reference to the DAO library.
  17.     Dim MyDb As DAO.Database          'This database.
  18.     Dim Rs As DAO.Recordset         'To retrieve the value to find.
  19.     Dim rsMVF As DAO.Recordset      'Child recordset to use for multi-value fields.
  20.     Dim varResult As Variant        'Return value for function.
  21.     Dim strSql As String            'SQL statement.
  22.     Dim strOut As String            'Output string to build up (multi-value field.)
  23.     Dim lngLen As Long              'Length of string.
  24.     Const strcSep = ","             'Separator between items in multi-value list.
  25.  
  26.     'Initialize to null.
  27.     varResult = Null
  28.  
  29.     'Build the SQL string.
  30.     strSql = "SELECT TOP 1 " & Expr & " FROM " & Domain
  31.     If Not IsMissing(Criteria) Then
  32.         strSql = strSql & " WHERE " & Criteria
  33.     End If
  34.     If Not IsMissing(ORDERClause) Then
  35.         strSql = strSql & " ORDER BY " & ORDERClause
  36.     End If
  37.     strSql = strSql & ";"
  38.  
  39.     'Lookup the value.
  40.     Set MyDb = CurrentDb
  41.  
  42.     Set Rs = MyDb.OpenRecordset(strSql, dbOpenForwardOnly)
  43.     If Rs.RecordCount > 0 Then
  44.         'Will be an object if multi-value field.
  45.         If VarType(Rs(0)) = vbObject Then
  46.             Set rsMVF = Rs(0).value
  47.             Do While Not rsMVF.EOF
  48.                 If Rs(0).Type = 101 Then        'dbAttachment
  49.                     strOut = strOut & rsMVF!filename & strcSep
  50.                 Else
  51.                     strOut = strOut & rsMVF![value].value & strcSep
  52.                 End If
  53.                 rsMVF.MoveNext
  54.             Loop
  55.             'Remove trailing separator.
  56.             lngLen = Len(strOut) - Len(strcSep)
  57.             If lngLen > 0& Then
  58.                 varResult = Left(strOut, lngLen)
  59.             End If
  60.             Set rsMVF = Nothing
  61.         Else
  62.             'Not a multi-value field: just return the value.
  63.             varResult = Rs(0)
  64.         End If
  65.     End If
  66.     Rs.Close
  67.  
  68.     'Assign the return value.
  69.     ELookup = varResult
  70.  
  71. Exit_ELookup:
  72.     Set Rs = Nothing
  73.     Set MyDb = Nothing
  74.     Exit Function
  75.  
  76. Err_ELookup:
  77.     Dialog.RichBox "Error " & Err & " " & Err.Description, vbExclamation, "ELookup Error " & Err.Number
  78.     Resume Exit_ELookup
  79.  
  80. End Function
  81.  
  82.  
Phil
Jun 18 '16 #2
TheSmileyCoder
2,322 Expert Mod 2GB
If you are just looking to see if a SINGLE record exists, you will be hard pressed to find any NOTICEABLE difference in performance.

In that case, I would use Dlookup, simply because its a one-line statement, i.e. less code to maintain, and document.
If you find your Dlookup is slow, then it is likely that your index have not been defined properly for the use case scenario.

Now if you are looking up many records, its a quite different matter.
Jun 19 '16 #3
NeoPa
32,556 Expert Mod 16PB
Phil:
IMO the recordset approach is faster, because it uses indexes
I believe DLookup() also uses indexes Phil.

I have a table of over 1.6 million records in SQL Server. When I open it from Access and go to the last record it takes just over two seconds, every time (So not affected by cacheing).

When I do a DLookup() for the last known record it takes no discernable time. Even more telling, when I request a record that doesn't exist it also returns the Null value immediately.

This clearly means that DLookup() uses indexes, just as one would expect.

As Smiley indicates, there are many situations where using DLookup() can be a massive performance hit. These are generally when trying to use it from within SQL though. One shouldn't say to avoid that at all costs, as Phil introduced a scenario where it can be helpful, but certainly treat with extreme caution.
Jun 26 '16 #4
zmbd
5,501 Expert Mod 4TB
I have found the same thing as TheSmileyCoder and NeoPa when using either DLOOKUP() or DAO.Recordset in the little databases I typically use.

My general rule(s) of thumb is this:
+ I avoid D-Functions in queries/SQL whenever possible as there is a slight performance hit as TheSmileyCoder points out in my smaller databases - I can only imagine that such hits would be worse on very large databases.
+ If I already have a recordset open, or will need that recordset later in the procedure then I use/open that recordset for the find/seek methods. (I often have recordsets open at a global level because more than one procedure will use it; however, that's another story :) )
+ If I do not have a recordset open then I tend to use the D-Functions.
Sort of the same phlosphy that Mr. Browne appears to express here (the highlight is mine :) ):
Allen Browne Getting a value from a table: DLookup()(read more)

Sooner or later, you will need to retrieve a value stored in a table. If you regularly make write invoices to companies, you will have a Company table that contains all the company's details including a CompanyID field, and a Contract table that stores just the CompanyID to look up those details. Sometimes you can base your form or report on a query that contains all the additional tables. Other times, DLookup() will be a life-saver.
Jun 26 '16 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Dalan | last post by:
I presume that using an open recordset method is the preferred method of accomplishing what I'm trying to do. Of course, if there are other options that would work, feel free to share them. I...
11
by: WindAndWaves | last post by:
Hi everyone, I hope I will not get banned for asking toooo many questions. I am just really excited to have this platform ;-) I have the following function: Function IsProperty(pptname) as...
5
by: j.mandala | last post by:
Someone is trying to run my Access 2002 database under Access 2003. He has had a number of problems: 1) i used the MSComCt2.ocx for it's Date and Time picker. I can't find it under 2003. Do I...
4
by: Will | last post by:
Hi, I had a DCount within a module on records in a table where CustSuffix = 0. I now need to DCount where CustSuffix = 0 and the type of cost Suffix (Suffix in table) = G. I can't get both...
3
by: RBohannon | last post by:
I've developed a database in Access 2000 on Windows 2000. I have been asked to put the database on a machine running Windows XP. I copied the database onto the XP machine with some data already...
13
by: MLH | last post by:
Suppose I have this simple SQL string... SELECT tblDrivers.DriverID, tblDrivers.DName FROM tblDrivers WHERE (((tblDrivers.DName) Like "N*")) ORDER BY tblDrivers.DriverID; And suppose that...
1
by: Sheldon Mopes | last post by:
I have read a few articles that state that a multi-user app over a network will run faster if DSum & DCount functions are replaced with SQL statements replicating the functions. As I am a novice to...
1
by: maxjake | last post by:
Hi I am using the following 'On Load' It is working correctly to show me MOT's that are due and after it has found the MOTs due it then shows me what TAX is due (from the similar code as below...
5
by: sudarp | last post by:
hello, I am wirting a function in VBA that adds a new record to an existing database. If i try to add a record with a primary key that already exists in the database, i get an error. I was...
8
by: Susan Bricker | last post by:
I have used DCount() to determine the number of records in a recordset. Silly me ... I just noticed that DCount returns an INTEGER, which can hold a maximum value of 32,767. What if the recordset...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.