11

I have a Microsoft SQL database, where i am trying to insert some data. I have a unique key on 4 columns and i want to insert data from multiple tables into this table while checking the data to make sure it will not violate the uniqueness of the key. If i was doing this on a single column, i would do a NOT IN, like so..

INSERT TABLE_A (FLD_1)
    SELECT FLD_1
        FROM TBL_B
        INNER JOIN TBL_C
            ON TBL_B.FLD_1 = TBL_C.FLD_1
    WHERE TBL_B.FLD_1 NOT IN
        (
        SELECT TBL_A.FLD_1 FROM TBL_A
        )

Any thoughts?

2 Answers 2

16

Use NOT EXISTS instead since you have to deal with multiple columns.

http://www.techonthenet.com/sql/exists.php

EDIT:

Untested, but roughly it will be this:

SELECT FLD_1
FROM TBL_B
INNER JOIN TBL_C  ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE NOT EXISTS 
    (
    SELECT TBL_A.FLD_1 FROM TBL_A INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1
    )

For a multi-column check it would be roughly this:

SELECT FLD_1, FLD_2, FLD_3, FLD_4)
FROM TBL_B
INNER JOIN TBL_C  ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE NOT EXISTS 
    (
    SELECT TBL_A.FLD_1, TBL_A.FLD_2, TBL_A.FLD_3, TBL_A.FLD_4 
    FROM TBL_A 
    INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1 AND 
                        TBL_B.FLD2 = TBL_A.FLD2 AND 
                        TBL_B.FLD3 = TBL_A.FLD3 AND 
                        TBL_B.FLD4 = TBL_A.FLD4 
    )
1
  • So use IF NOT EXISTS in the beginning, or WHERE NOT EXISTS in the WHERE clause? Could you possibly provide syntax? It would greatly appreciated.
    – Kyle
    Aug 4, 2010 at 15:30
1

Also EXCEPT keyword can be used.

SELECT FLD_1, FLD_2, FLD_3, FLD_4)
FROM TBL_B
INNER JOIN TBL_C  ON TBL_B.FLD_1 = TBL_C.FLD_1

EXCEPT

SELECT TBL_A.FLD_1, TBL_A.FLD_2, TBL_A.FLD_3, TBL_A.FLD_4 
FROM TBL_A 
INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1 AND 
                    TBL_B.FLD2 = TBL_A.FLD2 AND 
                    TBL_B.FLD3 = TBL_A.FLD3 AND 
                    TBL_B.FLD4 = TBL_A.FLD4 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.