1

我正在尝试将一个表中的键添加到另一个表中,以便创建一对多关系。我要添加外键的表当前包含员工的名字和姓氏,但没有 ID。我想根据他们的名字和姓氏查询员工表以找到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)

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

4

1 回答 1

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)

...不起作用,因为dbo.InjuryOLD在任何 FROM 子句中都没有引用。您可能打算将dbo.InjuryOLDExists 子查询的 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)
于 2012-05-25T17:19:02.653 回答