2015-11-05 111 views
-4

CREATE TABLE間( RoomID爲nvarchar(8)PRIMARY KEY, 容量數字(3)嘗試在sql中創建外鍵時出現錯誤?

CREATE TABLE RoomType( RoomType nvarchar的(2)主鍵, 描述爲nvarchar(20), 責任管理爲nvarchar(20) )

ALTER TABLE房

附加約束fk_type外鍵(類型)引用室類型(Type)

主要錯誤0x80040E11,次要錯誤0

ALTER TABLE房 附加約束fk_type外鍵(類型)引用RoomType(類型) 無效的列ID。 [類型]

+0

你想命名你正在創建的表的名字是什麼?你想在那張桌子上放什麼樣的領域?哪些表和字段應該參與外鍵關係? – zedfoxus

+0

我想要創建RoomID和設備類型以將房間與設備關聯,因此新表格將稱爲RoomEquipment。 @zedfoxus – salman12

+0

好的,RoomEquipment是桌子。它將有RoomID和EquipmentType字段。 RoomEquipment的EquipmentType字段將與Equipment的EquipmentType字段相關。 RoomEquipment的RoomID字段與任何東西有關嗎? – zedfoxus

回答

0

您可以創建結合RoomID和EquipmentType像這樣的表RoomEquipment:

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

+0

我已添加表房間。 – salman12

+0

檢查我在哪裏使用適當的外鍵創建'RoomEquipment'表的第一個代碼塊。這對你有用嗎? – zedfoxus

+0

在我的任務中,它表示我們不允許組合任何表格,但這確實有助於感謝。 – salman12

相關問題