尝试在sql中创建外键时继续出错?

时间:2015-11-05 20:59:46

标签: sql sql-server-2008

CREATE TABLE Room( RoomID nvarchar(8)PRIMARY KEY, 容量数字(3)

CREATE TABLE RoomType( RoomType nvarchar(2)主键, 描述nvarchar(20), 责任nvarchar(20) )

alter table Room

添加约束fk_type外键(Type)引用RoomType(Type)

主要错误0x80040E11,次要错误0

  

改变房间   添加约束fk_type外键(类型)引用RoomType(Type)   列ID无效。 [类型]

1 个答案:

答案 0 :(得分:0)

您可以创建一个RoomEquipment表,它将RoomID和EquipmentType组合在一起,如下所示:

create table RoomEquipment (
  RoomID int,
  EquipmentType nvarchar(1),
  primary key (roomid, equipmenttype),
  constraint fk_roomequipment_equipment_type 
             foreign key (equipmenttype) 
             references equipment(equipmenttype),
  constraint fk_roomequipment_equipment_roomid
             foreign key (roomid) 
             references room(roomid)
);

其他表格可能如下所示:

-- I prefer using char datatype for predictable number of characters in a field
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
);

-- You could use char(1) instead of nvarchar(1) for type; I'd prefer using int instead
create table Equipment (
Equipmenttype nvarchar(1) NOT NULL,
Description nvarchar(10)
);

-- Added a unique key to assist with good foreign key relationship
alter table Equipment add constraint uk_equipment_equipmenttype unique (equipmenttype);

-- Just use an int or char if roomID length is predictable
Create table Room (
RoomID nvarchar(8),
Capacity numeric(3),
Roomtype(fk,nvarchar(2)
);

alter table room add constraint uk_room_id unique (roomid);

示例在这里:http://sqlfiddle.com/#!3/f510b