Aggregate function to do concatenation ~ create a delimited list

A simplistic concatenation aggregate function for Access (which maintains one advantage(?) over this mvp solution ~ that is we can define our queries outside of the code):

A sample query, saved here as ‘QuerySelectionForConcatenation’:

SELECT DISTINCT valid_value.value_txt
 FROM valid_value
 WHERE valid_value.value_set_cde = [InputId]

How to call it (within another query):

SELECT ConcatenateListByString("QuerySelectionForConcatenation", MyTable.value_set_cde, ",")
FROM MyTable


The function(s) themselves (one function for number foreign keys and another for text foreign keys):

Public Function ConcatenateList(ByVal queryName As String, ByVal fkId As Long, ByVal delimiter As String) As String
    Dim qryDef As QueryDef
    Dim rs As Recordset
    Dim str As String
    str = ""

    Set qryDef = CurrentDb.QueryDefs(queryName)
    qryDef.Parameters("InputId") = fkId
    Set rs = qryDef.OpenRecordset(dbOpenForwardOnly)

    If (Not rs.EOF) Then
        str = rs(0)
        rs.MoveNext
    End If

    Do While Not rs.EOF
        str = str & delimiter & rs(0)
        rs.MoveNext
    Loop

    rs.Close
    Set rs = Nothing
    Set qryDef = Nothing

    ConcatenateList = str
End Function

If your foreign key is a string / text:

Public Function ConcatenateListByString(ByVal queryName As String, ByVal fkId As String, ByVal delimiter As String) As String
    Dim qryDef As QueryDef
    Dim rs As Recordset
    Dim str As String
    str = ""

    Set qryDef = CurrentDb.QueryDefs(queryName)
    qryDef.Parameters("InputId") = fkId
    Set rs = qryDef.OpenRecordset(dbOpenForwardOnly)

    If (Not rs.EOF) Then
        str = rs(0)
        rs.MoveNext
    End If

    Do While Not rs.EOF
        str = str & delimiter & rs(0)
        rs.MoveNext
    Loop

    rs.Close
    Set rs = Nothing
    Set qryDef = Nothing

    ConcatenateListByString = str
End Function

One Response

  1. Thank you, this bit of code was a huge help. I also like your smiley on the side :)

Leave a Reply