Search code examples
sqlwhere-clauseexists

SQL Insert INTO - adding non existing IDs


I am trying to clean up the data in a table so that I can create a 1 to 1 relationship. The table with the primary key has more records than the table it shares the 1 to 1 relationship with. To solve this problem I am trying to insert the missing ID's from table 2 into table 2.

INSERT INTO medical_Surveillance(dbo.Medical_surveillance.EmpID)
SELECT dbo.EmployeeInformation.EmpID
FROM EmployeeInformation
WHERE not exists (select dbo.medical_Surveillance.EmpID from medical_Surveillance
WHERE dbo.medical_Surveillance.EmpID = dbo.EmployeeInformation.EmpID)

What is wrong with this SQL statement? When ran it tries to insert values into columns other than dbo.Medical_surveillance.EmpID.


Solution

  • You can do the same thing with a left join:

    INSERT INTO medical_Surveillance(EmpID)
    SELECT EmployeeInformation.EmpID
    FROM EmployeeInformation
        LEFT JOIN medical_surveillance ON EmployeeInformation.EmpID = medical_surveillance.EmpID
    WHERE medical_surveillance.EmpID IS NULL