Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert rows in table if not found in another table

Tags:

sql-server

I have a table:

Employee (employeeID)
EmployeeRank (rankID, employeeID)

Now I have another table that has all the employee's that are going to get a raise.

DueForRaise (rankID, employeeID)

I have to insert all the employees that are in DUeForRaise into the EmployeeRank table ONLY if they are not already there with the same rank.

I am doing this update for a particlar rankID, @rankID.

Would this work?

INSERT EmployeeRank ( rankID, employeeID)
SELECT rankID, employeeID
FROM DueForRaise dfr
      OUTER JOIN EmployeeRank er er.employeeid = dfr.employeeid)
WHERE dfr.rankID = @rankID
like image 806
mrblah Avatar asked Dec 18 '22 05:12

mrblah


1 Answers

How about:

insert into EmployeeRank
select * from DueForRaise p
where NOT EXISTS(
    SELECT * FROM EmployeeRank WHERE rankID=p.rankID and employeeID=p.employeeID
);
like image 87
Nestor Avatar answered Dec 31 '22 11:12

Nestor