Pteridium
Pteridium

Reputation: 23

custom function too slow

I have created a custom function that is used in a query. The function opens a small table (50 cells) and adds a date to one column in the query based on lookup results. The function performs too slowly though and I think it may be because I open and close the record set for every record in the query. Is there a way to avoid opening the record set and closing it every time the function is called? I suspect this defeats the purpose of using a function in the first place but am hoping someone has a solution.

Added after original post.

Based on the structures below, I need to get the Description from the table into the CustomFunctionField in the query and the date fields are the connection. The table holds the date range and the query has specific dates in the date range.

--Query-- ID | Info | Date | CustomFunctionField

--Table-- ID | StartDate | EndDate | Description

Following is the code:

Public Function SelectTerm(DateFull)

    Dim rstin As DAO.Recordset
    Dim dx As Date
    Dim dterm As String

    Set rstin = CurrentDb.OpenRecordset("tblTerms", dbOpenSnapshot)

    dx = "1/1/2000"

    If Not rstin.EOF And Not rstin.BOF Then
        Do Until rstin.EOF Or dx >= DateFull
            dx = rstin.Fields("DateEnd")
            rstin.MoveNext
        Loop

        rstin.MovePrevious
        dterm = rstin.Fields("Description")
        rstin.Close
    End If

    SelectTerm = dterm

End Function

Upvotes: 2

Views: 328

Answers (1)

HansUp
HansUp

Reputation: 97101

Use a correlated subquery to look up the term description from tblTerms based on a Date/Time field, DateFull, in your main table.

SELECT
    y.DateFull,
    (
        SELECT TOP 1 [Description]
        FROM tblTerms
        WHERE DateEnd <= y.DateFull
        ORDER BY DateEnd DESC
    ) AS term_description
FROM YourTable AS y;

Correlated subqueries aren't exactly known for blazing performance. However, this approach should be much faster than a UDF which opens a recordset and moves through the rows until it finds the value you want.

Upvotes: 1

Related Questions