June 27, 2013 at 8:53 am
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)
June 27, 2013 at 8:58 am
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
June 27, 2013 at 9:01 am
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)
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
June 27, 2013 at 9:08 am
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
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy