为什么表Room
不接受外键?
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3)
)
ALTER TABLE Room
add foreign key(Roomtype)
references RoomType(Roomtype)
这是我运行alter table时收到的错误消息。
重大错误0x80040E11,轻微错误0 更改桌子室 添加外键(Roomtype) 参考RoomType(Roomtype) 列ID无效。 [Roomtype]
答案 0 :(得分:0)
在尝试声明外键约束之前,需要将外键作为字段添加到Room表中。
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3)
)
ALTER TABLE Room
ADD Roomtype nvarchar(2) NOT NULL
ALTER TABLE Room
add constraint FK_Give_Me_A_Good_Name foreign key(Roomtype)
references RoomType(Roomtype)
答案 1 :(得分:0)
在您可以FK之前,该列必须存在。
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3),
RoomtypeA nvarchar(2) NOT NULL
)
ALTER TABLE [dbo].[Room] ADD CONSTRAINT FK_MyName FOREIGN KEY (RoomtypeA) REFERENCES dbo.Roomtype (Roomtype)
GO