SQL Insert into Exists - 将外键添加到现有表

时间:2012-05-25 17:03:41

标签: sql insert exists

我正在尝试将一个表从一个表添加到另一个表,以便我可以创建一对多的关系。我想添加外键的表目前有员工的名字和姓氏,但不是ID。我想查询employee表,根据他们的名字和姓氏找到ID,然后将其添加到伤害表中。

我继续收到以下错误:

The multi-part identifier "InjuryOLD.FirstName" could not be bound.
The multi-part identifier "dbo.InjuryOLD.LastName" could not be bound.

以下是SQL语句:

Insert into dbo.InjuryOLD(dbo.InjuryOLD.EmpID)
Select dbo.EmployeeInformation.EmpID
From EmployeeInformation
Where exists(select dbo.EmployeeInformation.EmpID from dbo.EmployeeInformation
             where dbo.EmployeeInformation.FirstName = dbo.InjuryOLD.FirstName 
             and dbo.EmployeeInformation.LastName = dbo.InjuryOLD.LastName)

我已经确保我引用的表格和列没有拼写错误,我知道两个员工可能有相同的名字。但是在这种情况下并非如此。

1 个答案:

答案 0 :(得分:3)

SELECT部分和INSERT声明应该始终有效

所以...

Select dbo.EmployeeInformation.EmpID
From EmployeeInformation
Where exists(select dbo.EmployeeInformation.EmpID from dbo.EmployeeInformation
             where dbo.EmployeeInformation.FirstName = dbo.InjuryOLD.FirstName 
             and dbo.EmployeeInformation.LastName = dbo.InjuryOLD.LastName)

...不起作用,因为在FROM子句中未引用dbo.InjuryOLD。您可能打算将dbo.InjuryOLD放在Exists子查询的from子句中,而不是重复EmployeeInformation

Select dbo.EmployeeInformation.EmpID
From EmployeeInformation
Where exists(select 1 from dbo.InjuryOLD  
             where
                 dbo.EmployeeInformation.FirstName = dbo.InjuryOLD.FirstName 
                 and dbo.EmployeeInformation.LastName = dbo.InjuryOLD.LastName)