我有一张桌子,称之为TBL.它有两列,称为A和B.现在在查询中我需要一列作为A,其他列应该是所有B的逗号分隔列表,它们在TBL中对抗A. 例如TBL是这样的
1阿尔法
2 Beta
1 Gamma
1达美
查询结果应该是
1 Alpha,Gamma,Delta
2 Beta
这种类型的东西很容易用存储过程中的游标.但我无法通过MS Access来实现,因为它显然不支持存储过程.有没有办法在MS访问中运行存储过程?或者有没有办法通过SQL来运行这种类型的查询
您可以使用用户定义函数(UDF)连接记录.
下面的代码可以"按原样"粘贴到标准模块中.您的示例SQL将是:
SELECT tbl.A, Concatenate("SELECT B FROM tbl WHERE A = " & [A]) AS ConcA FROM tbl GROUP BY tbl.A
此代码是由DHookom,访问MVP,并取自http://www.tek-tips.com/faqs.cfm?fid=4233
Function Concatenate(pstrSQL As String, _ Optional pstrDelim As String = ", ") _ As String 'example 'tblFamily with FamID as numeric primary key 'tblFamMem with FamID, FirstName, DOB,... 'return a comma separated list of FirstNames 'for a FamID ' John, Mary, Susan 'in a Query '(This SQL statement assumes FamID is numeric) '=================================== 'SELECT FamID, 'Concatenate("SELECT FirstName FROM tblFamMem ' WHERE FamID =" & [FamID]) as FirstNames 'FROM tblFamily '=================================== ' 'If the FamID is a string then the SQL would be '=================================== 'SELECT FamID, 'Concatenate("SELECT FirstName FROM tblFamMem ' WHERE FamID =""" & [FamID] & """") as FirstNames 'FROM tblFamily '=================================== '======For DAO uncomment next 4 lines======= '====== comment out ADO below ======= 'Dim db As DAO.Database 'Dim rs As DAO.Recordset 'Set db = CurrentDb 'Set rs = db.OpenRecordset(pstrSQL) '======For ADO uncomment next two lines===== '====== comment out DAO above ====== Dim rs As New ADODB.Recordset rs.Open pstrSQL, CurrentProject.Connection, _ adOpenKeyset, adLockOptimistic Dim strConcat As String 'build return string With rs If Not .EOF Then .MoveFirst Do While Not .EOF strConcat = strConcat & _ .Fields(0) & pstrDelim .MoveNext Loop End If .Close End With Set rs = Nothing '====== uncomment next line for DAO ======== 'Set db = Nothing If Len(strConcat) > 0 Then strConcat = Left(strConcat, _ Len(strConcat) - Len(pstrDelim)) End If Concatenate = strConcat End Function