Sql server 可以从外键引用非主键列吗?
这是表1,我想将指定ID引用到另一个表,但它不起作用Sql server 可以从外键引用非主键列吗?,sql-server,Sql Server,这是表1,我想将指定ID引用到另一个表,但它不起作用 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
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),
)
您的创建不正确。试着这样做:
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)
)
许多员工都与某个名称相关。一对多关系。您创建的关系不正确。试着这样做:
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)
)
许多员工都与某个名称相关。一对多关系。表#2中的外键必须引用表#1中的主键(除完整的主键外)或唯一索引的任何非空列。因此,如果您有一列(或一组列)是唯一的,那么您可以在该列上放置一个唯一索引,并引用该列。表2中的外键必须引用表1中的主键(除完整主键外)或唯一索引的任何非空列。因此,如果您有一列(或一组列)是唯一的,那么您可以在该列上放置唯一索引并引用该列。