基于来自另一个表的数据更新表的解决方案

时间:2010-06-07 19:24:59

标签: sql ms-access vba

我有2个访问表

这就是我需要的:

1. if the PK from table1 exists in table2, then delete the entire record with that PK from table2 and add the entire record from table1 into table2
2. if the PK does not exist then add the record

我需要有关sql语句和VBA的帮助

我猜VBA应该是一个循环,遍历table1中的每个记录。在循环中我应该有select语句

3 个答案:

答案 0 :(得分:1)

我会在两个陈述中这样做。一个删除正确的行,另一个删除行。

Dim oDB As DAO.Database
Dim sSQL As String
Dim oQry As DAO.QueryDef

Set oDB = DBEngine.Workspaces(0).Databases(0)
sSQL = "Delete From Table2 Where Exists( Select 1 From Table1 Where Table1.Id = Table2.Id )"
oDB.Execute sSQL, dbFailOnError

sSQL = "PARAMETERS [Col1Param] Text, [Col2Param] Text, [Col2Param] Text; " & _
    "Insert Into Table1(Col1, Col2, Col3) Values([Col1Param], [Col2Param], [Col3Param])"
Set oQry = oDB.CreateQueryDef("", sSQL)
oQry!Col1Param = "Col1Value"
oQry!Col2Param = "Col2Value"
oQry!Col3Param = "Col3Value"
oQry.Execute, dbFailOnError

oQry.Close

Set oQry = Nothing
Set oDB = Nothing

答案 1 :(得分:1)

我认为你不需要VBA循环,只需要两个SQL语句。

首先从table2中删除匹配的行。

DELETE 
FROM table2 AS m
WHERE pk IN (SELECT pk FROM table1);

然后将table1中的所有行追加到table2中。

INSERT INTO table2 (
    pk,
    field2,
    field3,
    field4)
SELECT
    i.pk,
    i.field2,
    i.field3,
    i.field4
FROM
    table1 AS i;

答案 2 :(得分:1)

DELETE FROM table2
  WHERE EXISTS
  (SELECT * FROM table1, table2
   WHERE table1.pk=table2.pk);

INSERT INTO table2
SELECT * FROM table1;

这假定table1table2具有相同的列。