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

前端 未结 10 1588
无人及你
无人及你 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:36

    To accomplish your task you will need to use code. One solution, using more meaningful names, is as follows:

    Main table with two applicable columns:

    Table Name: Widgets

    Field 1: ID (Long)

    Field 2: Color (Text 32)

    Add table with two columns:

    Table Name: ColorListByWidget

    Field 1: ID (Long)

    Field 2: ColorList (Text 255)

    Add the following code to a module and call as needed to update the ColorListByWidget table:

    Public Sub GenerateColorList()
    
    Dim cn As New ADODB.Connection
    Dim Widgets As New ADODB.Recordset
    Dim ColorListByWidget As New ADODB.Recordset
    Dim ColorList As String
    
    Set cn = CurrentProject.Connection
    
    cn.Execute "DELETE * FROM ColorListByWidget"
    cn.Execute "INSERT INTO ColorListByWidget (ID) SELECT ID FROM Widgets GROUP BY ID"
    
    With ColorListByWidget
       .Open "ColorListByWidget", cn, adOpenForwardOnly, adLockOptimistic, adCmdTable
       If Not (.BOF And .EOF) Then
          .MoveFirst
          Do Until .EOF
             Widgets.Open "SELECT Color FROM Widgets WHERE ID = " & .Fields("ID"), cn
             If Not (.BOF And .EOF) Then
                Widgets.MoveFirst
                ColorList = ""
                Do Until Widgets.EOF
                   ColorList = ColorList & Widgets.Fields("Color").Value & ", "
                   Widgets.MoveNext
                Loop
             End If
             .Fields("ColorList") = Left$(ColorList, Len(ColorList) - 2)
             .MoveNext
             Widgets.Close
          Loop
       End If
    End With
    
    
    End Sub
    

    The ColorListByWidget Table now contains your desired information. Be careful that the list (colors in this example) does not exceed 255 characters.

提交回复
热议问题