INSERT Statement

  • I am looking to insert data into a table if the data is not already in the table. Is the below the correct statement to accomplish this?

    INSERT INTO DSD

    (req_id

    ,value

    ,comments

    ,create_date

    ,modify_date

    ,modify_by

    ,peps_id

    ,place_id

    ,act_date

    )

    SELECT DISTINCT

    smf6.req_id

    ,smf6.value

    ,smf6.comments

    ,smf6.create_date

    ,smf6.modify_date

    ,smf6.modify_by

    ,smf6.student_id

    ,smf6.place_id

    ,smf6.act_date

    FROM smf6

    WHERE (smf6.RespID + smf6.req_id + smf6.peps_id)

    NOT IN (SELECT DSD.modify_by, DSD.req_id + DSD.peps_id

    from DSD)

  • i typically join the table against the insert/target table with a left join

    it seems like the unique criteria you are using is the three columns i'm using in the join? is that right?

    INSERT INTO DSD (

    req_id,

    value,

    comments,

    create_date,

    modify_date,

    modify_by,

    peps_id,

    place_id,

    act_date

    )

    SELECT DISTINCT smf6.req_id,

    smf6.value,

    smf6.comments,

    smf6.create_date,

    smf6.modify_date,

    smf6.modify_by,

    smf6.student_id,

    smf6.place_id,

    smf6.act_date

    FROM smf6

    LEFT JOIN DSD

    ON smf6.modify_by = DSD.modify_by

    AND smf6.req_id = DSD.req_id

    AND smf6.peps_id = DSD.peps_id

    WHERE DSD.req_id IS NULL --no match found

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Or NOT EXISTS. Both compare columns individually rather than concatenating them together which can give rise to false matches.

    WHERE NOT EXISTS (

    SELECT 1 FROM DSD

    WHERE DSD.modify_by = smf6.RespID AND DSD.req_id = smf6.req_id AND DSD.peps_id = smf6.peps_id)

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • You could do something like

    insert into tab1

    select ________ from tab2

    except

    select ________ from tab1

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply