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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Need help on sql code If Not Exists...Then Insert

Author  Topic 

dejanc
Starting Member

8 Posts

Posted - 2011-01-05 : 04:48:49
Hello SqlTeam,
I have two tables in visual studio application imported from MSaccess. SecondName are uniq in both tables.
I want to write a code for NOT insert exists records from table Persons1 if they are already in table Persons2.
I have found that best way to us IF NOT EXISTS...THEN INSERT INTO. But, I`m new in programming, only SQL basics.
Need somone to show me how to write a code on below code.

So far I have write this code, but of course tables are without primary keys.
INSERT INTO Persons1
(FirstName, SecondName)
SELECT FirstName, SecondName
FROM Persons2


Thank you in advance for help to anyone!

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-01-05 : 04:56:42
INSERT INTO Persons1
(FirstName, SecondName)
SELECT FirstName, SecondName
FROM Persons2
where SecondName not in (select SecondName from Persons1)

is SecondName really unique?

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2011-01-05 : 04:58:54
[code]INSERT INTO Persons1
(FirstName, SecondName)
SELECT FirstName, SecondName
FROM Persons2 AS P2
WHERE NOT EXISTS (SELECT * FROM Persons1 AS P1 WHERE P1.FirstName = P2.FirstName AND P1.SecondName = P2.SecondName)

[/code]
edit Removed FirstName test. Or you could do it the way Nigel showed
Go to Top of Page

dejanc
Starting Member

8 Posts

Posted - 2011-01-05 : 07:37:31
Nigel, Kristen,
thank you both 1TB times for help. Both codes are working perfect.

This is my first question/thread, and answers has come as speed of light.

thanks again!
Go to Top of Page
   

- Advertisement -