MS Access SQL:使用update和replace来删除多个空格

时间:2014-02-24 10:37:36

标签: sql ms-access spaces

在MS Access中,我尝试使用:

UPDATE Table SET FieldName= REPLACE(FieldName, '\s+', '\s');

从字段中删除多个空格,但不起作用。

2 个答案:

答案 0 :(得分:4)

正如对问题的评论中所提到的,Replace()函数不支持正则表达式。但是,您可以使用以下VBA代码完成目标:

Option Compare Database
Option Explicit

Sub RemoveMultipleSpaces()
    Dim cdb As DAO.Database
    Set cdb = CurrentDb
    Do While DCount("FieldName", "TableName", "FieldName LIKE ""*  *""") > 0
        cdb.Execute "UPDATE TableName SET FieldName = Replace(FieldName,""  "","" "")"
    Loop
    Set cdb = Nothing
End Sub

编辑重新评论

或者,您可以使用以下代码使用正则表达式来查找替换候选项:

Option Compare Database
Option Explicit

Public Function RegexReplace( _
        originalText As Variant, _
        regexPattern As String, _
        replaceText As String, _
        Optional GlobalReplace As Boolean = True) As Variant
    Dim rtn As Variant
    Dim objRegExp As Object  ' RegExp

    rtn = originalText
    If Not IsNull(rtn) Then
        Set objRegExp = CreateObject("VBScript.RegExp")
        objRegExp.Pattern = regexPattern
        objRegExp.Global = GlobalReplace
        rtn = objRegExp.Replace(originalText, replaceText)
        Set objRegExp = Nothing
    End If
    RegexReplace = rtn
End Function

用法示例:

RegexReplace("This is     a test.","\s+"," ")

返回

This is a test.

您可以在这样的查询中使用它:

UPDATE TableName SET FieldName = RegexReplace(FieldName,'\s+',' ')

答案 1 :(得分:0)

此功能可删除多个空格以及制表符,换行符号等。

Public Function removeObsoleteWhiteSpace(FromString As Variant) As Variant
  If IsNull(FromString) Then 'handle Null values
    removeObsoleteWhiteSpace = Null
    Exit Function
  End If
  Dim strTemp As String
  strTemp = Replace(FromString, vbCr, " ")
  strTemp = Replace(strTemp, vbLf, " ")
  strTemp = Replace(strTemp, vbTab, " ")
  strTemp = Replace(strTemp, vbVerticalTab, " ")
  strTemp = Replace(strTemp, vbBack, " ")
  strTemp = Replace(strTemp, vbNullChar, " ")
  While InStr(strTemp, "  ") > 0
    strTemp = Replace(strTemp, "  ", " ")
  Wend
  strTemp = Trim(strTemp)
  removeObsoleteWhiteSpace = strTemp
End Function