简体   繁体   中英

MS Access: convert query results to string with delimiter

I need to view results of the query as a string with delimiter.

Example:

Table "Cars"

carId | carName
1 | Honda
2 | Ford

Table "Drivers"

driverId | driverName
1 | John

Table "Timetable"

tDate | tDriver | tCar
15/07/2014 | 1 | 1
15/07/2014 | 1 | 2

Query "UsedCars"

driver | car
1 | 1
1 | 2

I need the results in a query "UsedCars" to look like this:

driver | car
1 | 1;2

Any help will be much appreciated.

This is like a GROUP CONCAT in mySQL which is not available in MS Access. But there is a work around wherein you create a Function (via Module) in MS Access named GetList for example, so that you will have this query:

SELECT Driver, GetList("SELECT Car FROM UsedCars","",";") as Cars
FROM UsedCars
GROUP BY Driver

The Function using VBA is the one below:

Option Compare Database

Public Function GetList(SQL As String _
                        , Optional ColumnDelimeter As String = ", " _
                        , Optional RowDelimeter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
'   1. SQL is a valid Select statement
'   2. ColumnDelimiter is the character(s) that separate each column
'   3. RowDelimiter is the character(s) that separate each row
'RETURN VAL: Concatenated list
'DESIGN NOTES:
'EXAMPLE CALL: =GetList("Select Col1,Col2 From Table1 Where Table1.Key = " & OuterTable.Key)

Const PROCNAME = "GetList"
Const adClipString = 2
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim sResult As String

On Error GoTo ProcErr

Set oConn = CurrentProject.Connection
Set oRS = oConn.Execute(SQL)

sResult = oRS.GetString(adClipString, -1, ColumnDelimeter, RowDelimeter)

If Right(sResult, Len(RowDelimeter)) = RowDelimeter Then
   sResult = Mid$(sResult, 1, Len(sResult) - Len(RowDelimeter))
End If

GetList = sResult
oRS.Close
oConn.Close

CleanUp:
  Set oRS = Nothing
  Set oConn = Nothing

Exit Function

ProcErr:
' insert error handler
 Resume CleanUp

End Function

Source here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM