(Q) How can I extract all values of a field from a table which is the
related to another table in a 1:M relationship?
(A) The following function fConcatChild can be used in a query
SELECT Orders.*, fConcatChild("Order
Details","OrderID","Quantity","Long",[OrderID]) AS
SubFormValuesFROM Orders;
This example is based on Orders and Orders Details tables in Northwind database which are
related in a 1:M relationship. The fConcatChild simply states Concatenate all values in
field Quantity in table Order Details where linking field is OrderID of datatype Long, for
each value of [OrderID] returned by the table Orders.
Function fConcatChild(strChildTable As String, _
strIDName As String, _
strFldConcat As String, _
strIDType As String, _
varIDvalue As Variant) _
As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim varConcat As Variant
Dim strCriteria As String, strSQL As String
On Error GoTo Err_fConcatChild
varConcat = Null
Set db = CurrentDb
strSQL = "Select [" & strFldConcat & "] From [" & strChildTable & "]"
strSQL = strSQL & " Where "
Select Case strIDType
Case "String":
strSQL = strSQL & "[" & strIDName & "] = '" & varIDvalue & "'"
Case "Long", "Integer", "Double":
strSQL = strSQL & "[" & strIDName & "] = " & varIDvalue
Case Else
GoTo Err_fConcatChild
End Select
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot)
With rs
If .RecordCount <> 0 Then
Do While Not rs.EOF
varConcat = varConcat & rs(strFldConcat) & ";"
.MoveNext
Loop
End If
End With
fConcatChild = Left(varConcat, Len(varConcat) - 1)
Exit_fConcatChild:
If Not rs Is Nothing Then
rs.Close
Set rs = Nothing
End If
Set db = Nothing
Exit Function
Err_fConcatChild:
Resume Exit_fConcatChild
End Function
|