sql server programming:
[quoted text, click to view] On Tue, 09 Oct 2007 19:59:40 -0000, Kirk <loki70@hotmail.com> wrote:
>INSERT INTO FinalTable (Field2, Field3, Field 4)
>SELECT Field2, Field3, Field4
>>From TempTable
>WHERE (FinalTable.Field2 <> TempTable.Field2)
> AND (FinalTable.Field3 <> TempTable.Field3)
>
>For the above example, assume "Field1" [not shown] is a unique Primry
>Key/Auto Increment.
>
>In other words, if there is a record in the Final table that has the
>same Field2 & Field3 data, don't copy [insert] it.
There are three problems. One is in the logic of the WHERE clause.
When you test for "not equal" you can't just AND the two tests and get
the result you want. You would need
NOT (FinalTable.Field2 = TempTable.Field2
AND FinalTable.Field3 = TempTable.Field3)
I suggest you spend a few minutes with a few sample values and a truth
table to understand the difference. Or read up on boolean logic.
A second and larger problem is that the approach is that there is no
instance of FinalTable to really test against. If it were an UPDATE
you could use the reference in the UPDATE command, but an INSERT does
not reference existing rows in the target table. FinalTable has to
appear in a FROM clause somewhere in the SELECT.
Finally, what you need is a NOT EXISTS test in one form or another,
not the sort-of-join used. One way would be a LEFT OUTER JOIN with a
NULL test, but I prefer a NOT EXISTS test:
INSERT INTO FinalTable (Field2, Field3, Field 4)
SELECT Field2, Field3, Field4
FROM TempTable as A
WHERE NOT EXISTS
(SELECT * FROM FinalTable as B
WHERE A.Field2 = B.Field2
AND A.Field3 = B.Field3)
Roy Harvey