Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Veronica
Starting Member
6 Posts |
Posted - 2007-12-03 : 06:34:39
|
Hi Everyone, I have 2 tables. New_Candidates and Candidates. I'm trying to insert any new records of "New_Candidates" table into "Candidates", and if the [Candidate ID] (key) already exists, I would like the record to be updated instead. Does someone have some similar stored procedure code to help me do this ? (just basically a stored procedure to insert or update the records of one table to another). Any help is greatly appreciated.Thanks in Advance,Veronica,message_4_u2001@yahoo.com |
|
RickD
Slow But Sure Yak Herding Master
3608 Posts |
Posted - 2007-12-03 : 06:42:25
|
Why not just write one?if exists (select 1 from Candidates where CandidateID in (select CandidateID from New_Candidates)) begin update Candidates set col1 = col1 where CandidateID in (select CandidateID from New_Candidates) endif not exists (select 1 from Candidates where CandidateID in (select CandidateID from New_Candidates)) begin insert into Candidates (CandidateID, col1) select CandidateID, col1 from New_Candidates where CandidateID not in (select CandidateID from Candidates) end |
 |
|
Veronica
Starting Member
6 Posts |
Posted - 2007-12-03 : 06:45:57
|
Thank you for that ! I'll give it a go now... |
 |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2007-12-03 : 08:59:40
|
carefull of the second statement "if not exists". If some rows do but others don't you would skip the insert.As an alternative, this may perform better because you aren't using a "NOT IN" from a subquery that returns the all IDs from New_Candidates. New_Candidates may have very few rows so it may not matter but...--No IF necessary - if they join up then it exists, otherwise it doesn'tupdate c set c.col = nc.colfrom Candidates cjoin new_Candidates nc on nc.CandidateID = c.CandidateID--LEFT OUTER JOIN with WHERE ID is Null replaces the "if not exists (<select out the whole table>)"insert Candidates (colList)select colListfrom new_Candidates ncleft join Candidates c on c.candidateID = nc.candidateIDwhere c.CandidateID is NULL Be One with the OptimizerTG |
 |
|
Veronica
Starting Member
6 Posts |
Posted - 2007-12-03 : 09:24:50
|
yes, it's true, I'll give this statement a go thanks. |
 |
|
|
|
|