目的:在MS Access中使用SQL查询来查找与长文本字段中的特定关键字匹配的所有记录
我正在尝试查询MS Access DB中与字段中特定关键字列表匹配的所有记录。关键字如下:
AIN,ATIN,CKD,AKI,ARF
问题我遇到的是该字段是一个自由文本输入字段,因此数据的格式化遍布整个地方,我搜索的关键字通常会出现在中间其他全长单词(即AIN匹配" pAIN"," agAIN"等),而我只想在严格关键字的单词上包含匹配(即&#34 ; AIN"," AKI")。
我正在使用的想法是简单地包含符合以下格式的匹配:field_name like' * AIN *' .So基本上只包含之前有空格的匹配在关键字之后限制结果集中出现的误报数量。
我尝试编写一个SQL查询来规范化数据,以便出现所有其他字符("。","!","?&# 34;,"#"等等......将替换为空格字符(即" AIN!"将被替换(field_name,"!&# 34;,"")=" AIN")认为这应仅包含仅包含关键字的单词。在尝试在查询中运行我很长的嵌套替换语句时,我收到了#34; Query Too Complex"信息。嵌套替换如下:
UCASE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.REF_CONTENT_NM,chr(13)," "),chr(10)," "),"`"," "),"~"," "),"!"," "),"@"," "),"#"," "),"$"," "),"%"," "),"^"," "),"&"," "),"*"," "),"("," "),")"," "),"-"," "),"_"," "),"="," "),"+"," "),"["," "),"{"," "),"]"," "),"}"," "),";"," "),":"," "),","," "),"<"," "),"."," "),">"," "),"/"," "),"?"," "),"\"," "),"|"," "),""""," ")) like "* AIN *"
我相信解决方法是创建一个可以在SQL语句中引用的自定义函数,但我不完全确定如何实现这一点。基本上,我正在寻找关于如何评估如何规范化文本的解决方案的指导,如上面的嵌套替换语句,而不会遇到&#34;查询太复杂的消息&#34;。我觉得有一个简单的解决方案,我只是没有在这里看到,因此非常感谢指导!
答案 0 :(得分:1)
编写自定义函数来执行此操作的主要技巧是使用ParamArray
这是一个执行多次替换的小函数:
Public Function ReplaceMultiple(strInput As String, strReplace As String, ParamArray Find() As Variant) As String
Dim i As Long
ReplaceMultiple = strInput
For i = LBound(Find) To UBound(Find)
ReplaceMultiple = Replace(ReplaceMultiple, Find(i), strReplace)
Next
End Function
实施它:
ReplaceMultiple(a.REF_CONTENT_NM, " ", chr(13), chr(10), "`", "etc....")
但是,您可能需要考虑完全改变逻辑,例如,保留应该替换的字符表。我记得大约20-30个参数的最大数量,所以你可能需要两次使用ReplaceMultiple
。
如果您只是想用空格替换不是字符串的所有内容,可以尝试以下小函数:
Public Function ReplaceNonAlphanumeric(str As String) As String
If str = "" Then Exit Function
Dim i As Long
For i = 1 To Len(str)
If Mid(str, i, 1) Like "[0-9A-z]" Then
ReplaceNonAlphanumeric = ReplaceNonAlphanumeric & Mid(str, i, 1)
Else
ReplaceNonAlphanumeric = ReplaceNonAlphanumeric & " "
End If
Next
End Function