Does MS access(2003) have anything comparable to Stored procedure. I want to run a complex query in MS acceess

前端 未结 10 1625
无人及你
无人及你 2020-12-03 21:49

I have a table, call it TBL. It has two columns,call them A and B. Now in the query I require one column as A and other column should be a comma seprated list of all B\'s wh

10条回答
  •  孤城傲影
    2020-12-03 22:41

    You can concatenate the records with a User Defined Function (UDF).

    The code below can be pasted 'as is' into a standard module. The SQL for you example would be:

    SELECT tbl.A, Concatenate("SELECT B  FROM tbl
            WHERE A = " & [A]) AS ConcA
    FROM tbl
    GROUP BY tbl.A
    

    This code is by DHookom, Access MVP, and is taken from 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 
    

提交回复
热议问题