查询解析一个字段并显示它

Query to parse a field and display it

我有一个 table 值

Errors:
X_11;SR_4;D_11;SR_2
SR_4;T_22
E_18; E_28; SR_3; 
E_28; SR_3; 
SR_2;SR_4

我需要输入一个查询来解析这些值,以便出现任何带有 SR 的内容,所以我这样做 like "*SR*" 但在输出中我只需要显示这个:

Errors:
SR_4;SR_2
SR_4
SR_3 
SR_3 
SR_2;SR_4

我想在查询中使用除此之外的许多字段...而不是 VBA。我正在使用 MS Access 2010,我猜测是某种类型的解析,每个字段都用“;”分隔。那只会捕获SR吗?

我认为正则表达式可能是一个可行的方法。

在VBA中,您需要启用对"Microsoft VBScript Regular Expressions 5.5"的引用。 This question and its accepted answer 详细描述了什么是正则表达式以及如何在您的项目中启用它们(它适用于 Excel,但对于 Access 是相同的路线)。

启用引用后,这个小函数将为您提供一个 "clean" 字符串:

Public Function filterString(str As String)
    Dim re As RegExp, obj As Object, x As Variant, first As Boolean
    Set re = New RegExp
    With re
        .Global = True
        .IgnoreCase = True
        .MultiLine = False
        .Pattern = "SR_[0-9]" ' This will match the string "SR_" 
                              ' followed by a digit
    End With

    filterString = ""
    first = True

    If re.Test(str) Then
        Set obj = re.Execute(str)
        For Each x In obj
            If first Then
                first = False
            Else
                filterString = filterString & ";"
            End If
            filterString = filterString & x
        Next x
    End If
End Function

如果你测试它,你会看到结果是:

filterString("X_11;SR_4;D_11;SR_2")
  SR_4;SR_2

这就是你想要的结果。

现在,一个简单的 select 查询将为您提供所需的信息:

select filterString([Errors]) as err
from [yourTable]
where [yourTable].[Errors] like '*sr*'

希望对您有所帮助

我认为您可以通过将输入字符串拆分为一个数组然后使用 Filter 函数创建仅包含 SR_[=24= 的第二个数组来获得所需内容] 匹配第一个数组。最后 Join 生成包含匹配项的输出字符串的第二个数组。

Public Function filterString(ByVal pInput As String) As String
    Dim array1() As String
    Dim array2() As String
    array1 = Split(Replace(pInput, " ", vbNullString), ";")
    array2 = Filter(array1, "SR_")
    filterString = Join(array2, ";")
End Function

与正则表达式方式相比,该函数更加简洁。我觉得逻辑更简单。而且不需要设置引用

另请注意,它将容纳包含多个数字的 SR 代码(以防最终成为要求)。例如:

? filterString("X_11;SR_4;D_11;SR_234")
SR_4;SR_234

您可以按照@Barranka 建议的相同方式在查询中使用该函数:

SELECT filterString(y.Errors) AS sr_codes
FROM [yourTable] AS y
WHERE y.Errors Like '*sr*';