当前位置:  开发笔记 > 数据库 > 正文

MS access(2003)是否具有与存储过程相当的任何内容.我想在MS acceess中运行一个复杂的查询

如何解决《MSaccess(2003)是否具有与存储过程相当的任何内容.我想在MSacceess中运行一个复杂的查询》经验,为你挑选了1个好方法。

我有一张桌子,称之为TBL.它有两列,称为A和B.现在在查询中我需要一列作为A,其他列应该是所有B的逗号分隔列表,它们在TBL中对抗A. 例如TBL是这样的

1阿尔法

2 Beta

1 Gamma

1达美

查询结果应该是

1 Alpha,Gamma,Delta

2 Beta

这种类型的东西很容易用存储过程中的游标.但我无法通过MS Access来实现,因为它显然不支持存储过程.有没有办法在MS访问中运行存储过程?或者有没有办法通过SQL来运行这种类型的查询



1> Fionnuala..:

您可以使用用户定义函数(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 

推荐阅读
罗文彬2502852027
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有