1

一行我被給予了2個表(表-A,表-B)和SQL查詢,通過從同一列多個值循環爲

需要幫助的子查詢或可能的解決方案,以從TABLE_A.DESCRIPString

列中選擇多個值
TABLE_A: 
ID  PARTNUM  DESCRIPString 
1  4456  121~134~111 
2  4457  122~111 
3  4458  122~134 
4  4459  111 
5  4460  121~134~111 

CROSS MATCH與TABLE_B.DESCRIPID

TABLE_B: 
ID  DESCRIPID DECSRIPLong 
1  121   Silver 
2  122   Black 
3  111   Mask 
4  134   Pickle 

,最後顯示以下內容:

Table_AB 

ID  PARTNUM  DESCRIPString PARTDESCRIP 
1  4456  121~134~111  Silver~Pickle~Mask 
2  4457  122~111   Black~Mask 
3  4458  122~134   Black~Pickle 
4  4459  111    Mask 
5  4460  121~134~111  Silver~Pickle~Mask 

我明白大多數人會建議重做數據庫到每個列的單變量,但是在這種情況下無法完成。

回答

0

將此函數放入模塊並運行此查詢。它應該給你所要求的結果。你沒有指定數據類型,所以我使用了函數中的變體。

Public Function fnParseDescr(strWork As Variant) As String 
Dim vEnd 
Dim strTemp As String 
Dim strLook As String 
Dim strResult As String 
strResult = "" 
strWork = Trim(CStr(strWork)) 
Do While Len(strWork) > 0 
    If InStr(strWork, "~") = 0 Then 
     strLook = Trim(DLookup("[DESCRIPLong]", "TABLE_B", "[DESCRIPID] = CVar('" & strWork & "')")) 
     strResult = strResult & "~" & strLook 
     strWork = "" 
    Else 
     vEnd = InStr(strWork, "~") - 1 
     strTemp = Left(strWork, vEnd) 
     strLook = Trim(DLookup("[DESCRIPLong]", "TABLE_B", "[DESCRIPID] = CVar('" & strTemp & "')")) 
     strResult = strResult & "~" & strLook 
     strWork = Right(strWork, (Len(strWork) - (vEnd + 1))) 
     strTemp = "" 
     strLook = "" 
    End If 
Loop 
If Left(strResult, 1) = "~" Then strResult = Right(strResult, (Len(strResult) - 1)) 
fnParseDescr = strResult 
Exit Function 
End Function 


SELECT ID, 
    PARTNUM, 
    DESCRIPString, 
    fnParseDescr([DESCRIPString]) AS PARTDESCRIP 
FROM TABLE_A;