如何使用ms访问查询将一个列数据转换为ms访问中的多个行

时间:2015-05-23 19:36:19

标签: ms-access

我在ms访问表中的内容是

  1. 数字 购买
  2. 101 product1 product2 product3
  3. 102 product1 product2
  4. 我想使用ms访问查询(仅使用select查询)将其转换为以下格式

    1. 数字 购买
    2. 101 product1
    3. 101 product2
    4. 101 Product3
    5. 102 product1
    6. 102 product2
    7. 我无法将转换列转换为行,在表中我有一个列,其中多个值由空格分隔,我必须在ms访问选择查询中逐行转换它 请任何人都可以帮助我

1 个答案:

答案 0 :(得分:1)

如果您愿意使用代码,那么这很容易 使用以下代码计算空格数

Public Function calculateSplits(InputRecord as String) 
Dim recordWithoutSpaces as String
Dim noOfSpaces as Integer

recordWithoutSpaces = Replace(InputRecord," ","")
noOfSpaces =Len(InputRecord) -Len(recordWithoutSpaces )
calculateSplits = noOfSpaces 
End Function  

然后使用以下代码拆分记录

Public Function ParseText(TextIn As String, x As Byte, Optional MyDelim As String) As Variant
On Error Resume Next
If Len(MyDelim) > 0 Then
   ParseText = Split(TextIn, MyDelim)(x)
Else
   ParseText = Split(TextIn, " ")(x)
End If
End Function

然后,您只需创建一个读取表格的函数,并将记录追加到另一个根据需要拆分的表格

根据您的最新代码

Private Sub Command0_Click()
Dim myDelim As String
Dim strSQL As String ' want to insert the ParseText value into the new cust_info table
Dim ParseText As String
myDelim = " "
If Len(myDelim) > 0 Then
      For i = 0 To 3 ' <-- n+1 CalculateSplits e.g if you have found 3 splits (spaces) then i =0 to 4
         ParseText = Split("101 product1 product2 product3", myDelim)(i)
            strSQL = "INSERT INTO cust_info([cust_id], [cust_prods]) VALUES ('" & i + 1 & "','" & ParseText & "');"
         DoCmd.RunSQL strSQL
       Next


End If

End Sub

请注意我对i计数器上限的评论。

相关问题