MS Access:将查询结果转换为带分隔符的字符串

时间:2014-07-16 12:13:55

标签: sql access-vba

我需要将查询结果视为带分隔符的字符串。

示例:

表"汽车"

carId | carName
1 | Honda
2 | Ford

表"驱动程序"

driverId | driverName
1 | John

表"时间表"

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

查询" UsedCars"

driver | car
1 | 1
1 | 2

我需要查询结果" UsedCars"看起来像这样:

driver | car
1 | 1;2

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

这就像mySQL中的GROUP CONCAT,在MS Access中不可用。但是有一个解决方法,例如你在MS Access中创建一个名为GetList的函数(通过模块),这样你就可以得到这个查询:

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

使用VBA的功能如下:

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

来源here

答案 1 :(得分:0)