0

How can I delete non matching rows from a table? I have two tables that have a majority of related records. Table A must exist in table B. If table B record does not exist in table A delete table B record.

I am hoping there is a method to do this with a query rather then coding to populate a datatable and interating through each reocrd to see if there is a match.

TableA

keyID, foreignID, text

TableB

keyID, recordID, text

foriegnID and recordID are the related fields. I did not design these tables.

Somethins like this....

DELETE * FROM TableB WHERE (SELECT [foreignID] FROM TableA) <> recordID;

UPDATE: I can retireve the records needing to be deleted with query, but I would like to just delete them.

SELECT * FROM TableA LEFT JOIN TableB ON TableA.[foreignID] = TableB.[recordID] WHERE (((TableB.recordID) Is Null));

I am using vb.net to process a series of Access database.

4

1 回答 1

1

您可以在 Access SQL 中使用DCount 函数,无论查询是从 Access 会话内部运行还是从 VB.Net 或其他客户端代码外部运行,它都可以工作。

从查询开始,SELECT以确认它以正确的行为目标TableB

SELECT b.*
FROM TableB AS b
WHERE DCount("*", "TableA", "foreignID =" & b.recordID) = 0;

在人类语言中,该DCount表达式的意思是“给我 TableA 行的数量,其中 foreignID 值与当前 TableB 行的 recordID 值匹配”。 您想要识别该TableB计数为零的行。

foreignID注意我假设和都是数字数据类型recordID。如果它们是文本,则必须将 的值括b.recordID在引号中。

当您准备好触发时,转换为DELETE查询。

DELETE
FROM TableB AS b
WHERE DCount("*", "TableA", "foreignID =" & b.recordID) = 0;
于 2013-08-21T20:20:00.807 回答