可以从外键引用非主键列吗?

时间:2016-08-23 10:48:42

标签: sql-server

这是表格一,我想将DesignationId引用到其他表格,但它不起作用

create table Employees
(
    EmployeeID int identity(1,1) primary key,
    EmployeeNumber int not null,
    LocationID int not null,
    EmployeeName varchar(20) not null,
    DesignationID int not null,
    CategoryID int not null,
)

第二个表是..在第三行显示错误

create table Designation
(
    DesignationID int primary key ,
    JobTitle varchar(20) not null,

    CONSTRAINT fk_Designation_Employees 
        FOREIGN KEY (DesignationID) 
        REFERENCES Employees (DesignationID),
)

1 个答案:

答案 0 :(得分:4)

您正在创建此错误。请尝试这种方式:

create table Designation
(
    DesignationID int primary key ,
    JobTitle varchar(20) not null,

)

create table Employees
(
    EmployeeID int identity(1,1) primary key,
    EmployeeNumber int not null,
    LocationID int not null,
    EmployeeName varchar(20) not null,
    DesignationID int not null,
    CategoryID int not null,


    CONSTRAINT fk_Employees_Designation 
        FOREIGN KEY (DesignationID) 
        REFERENCES Designation (DesignationID)
)

许多员工与指定相关联。一对多的关系。