如果在另一个表中找不到,则在表中插入行

时间:2009-11-06 05:02:59

标签: sql-server

我有一张桌子:

Employee (employeeID)
EmployeeRank (rankID, employeeID)

现在我有另一张桌子,其中包括所有员工将要加薪。

DueForRaise (rankID, employeeID)

我必须将DUeForRaise中的所有员工插入到EmployeeRank表中,只要他们不在同一级别。

我正在为粒子rankID @rankID做这个更新。

这会有用吗?

INSERT EmployeeRank ( rankID, employeeID)
SELECT rankID, employeeID
FROM DueForRaise dfr
      OUTER JOIN EmployeeRank er er.employeeid = dfr.employeeid)
WHERE dfr.rankID = @rankID

2 个答案:

答案 0 :(得分:13)

怎么样:

insert into EmployeeRank
select * from DueForRaise p
where NOT EXISTS(
    SELECT * FROM EmployeeRank WHERE rankID=p.rankID and employeeID=p.employeeID
);

答案 1 :(得分:-1)

IF NOT EXISTS(SELECT * FROM EmployeeRank WHERE rankID = @rankID AND employeeID = @employeeID)

INSERT INTO EmployeeRank(rankID,employeeID)VALUES(@rankID,@ employeeID)