如何将一个表中的字符替换为另一个表的记录

时间:2013-11-13 04:46:46

标签: sql vba access-vba ms-access-2010

我在MSACCESS中有两个表。

表1

table1ID,txtOld,txtreplace,国

1,A,AA,德国

2,A,A,所有

3,A,A,挪威

4,A,A,所有

5,A,A,德国

表2

table2ID,姓,地址,国家

1,RonÄld,mäin街,德国

2,MÄdonä,park way,USA

3,Madonä,park way,挪威

我想根据table1上分配的国家/地区字符替换table2上的firstname和address上的特殊字符。如果国家/地区在table1上没有匹配或未分配,例如此处未分配美国,则它将替换与表1中的国家名称“all”匹配的字符。

1 个答案:

答案 0 :(得分:1)

不幸的是,我们无法在单个Access SQL查询中执行此操作,因此我们使用VBA:

enter image description here

Sub ReplaceAccentsInTable2()
'
  Dim rst As dao.Recordset
  Dim rst1 As dao.Recordset
'
  Set rst = CurrentDb.OpenRecordset("table2")
'
' replace first by country specific alphabet:
'
  Do While (Not rst.EOF)
    '
    Set rst1 = CurrentDb.OpenRecordset("SELECT txtOld, txtreplace" _
      & " FROM table1 WHERE (country='" & rst!Country & "');")
    '
    rst.Edit
    '
    While (Not rst1.EOF)
      rst!Firstname = Replace(rst!Firstname, rst1!txtOld, rst1!txtreplace, , , vbBinaryCompare)
      rst!Address = Replace(rst!Address, rst1!txtOld, rst1!txtreplace, , , vbBinaryCompare)
      rst1.MoveNext
    Wend
    '
    rst.Update
    rst.MoveNext
    '
  Loop
'
' replace then "all" alphabet: this is useful for Norway, as â is not set in table1:
'
  Set rst1 = CurrentDb.OpenRecordset("SELECT txtOld, txtreplace" _
    & " FROM table1 WHERE (country='all');")
'
  rst.MoveFirst
'
  Do While (Not rst.EOF)
    '
    rst.Edit
    rst1.MoveFirst
    '
    While (Not rst1.EOF)
      rst!Firstname = Replace(rst!Firstname, rst1!txtOld, rst1!txtreplace, , , vbBinaryCompare)
      rst!Address = Replace(rst!Address, rst1!txtOld, rst1!txtreplace, , , vbBinaryCompare)
      rst1.MoveNext
    Wend
    '
    rst.Update
    rst.MoveNext
    '
  Loop

'
' close ADO objects:
'
  rst1.Close
  Set rst1 = Nothing
'
  rst.Close
  Set rst = Nothing
'
End Sub

结果表2在这里:

enter image description here