将子表与已有外键的父表相关联

时间:2015-09-29 11:29:03

标签: sql sql-server

我有一个关系1酒店有N个房间。

饭店

Id (PK) identity

Name (UniqueKey)

Id (PK) identity

Number 

Name (UniqueKey)

HotelId (FK)

现在一个房间可以成为一个特殊的客房"。每个酒店只有一个房间。

如何将该关系与现有关系分配?

2 个答案:

答案 0 :(得分:0)

您应该在表(Room)上添加一个额外的列(col)并使用唯一索引

CREATE UNIQUE NONCLUSTERED INDEX UIX ON ROOM (col) where col = 1

答案 1 :(得分:0)

您应该在表Room上添加一个额外的列SpecialGuestRoomHotelID,允许NULL值并在该列上添加唯一索引;我还建议将其用作FK

ALTER TABLE Room ADD [SpecialGuestRoomHotelID] int NULL
CREATE UNIQUE NONCLUSTERED INDEX IX_Room_SpecialGuestRoomHotelID ON ROOM (SpecialGuestRoomHotelID)
ALTER TABLE [Room] WITH CHECK ADD CONSTRAINT [FK_Room_Hotel_SpecialGuest] FOREIGN KEY([SpecialGuestRoomHotelID]) REFERENCES Hotel ([Id])

EDIT 评论中提到的程序应该是这样的:

INSERT INTO Rooms (..., SpecialGuestRoomHotelID) VALUES(..., NULL)
-- Check for errors and get the newly inserted @RoomId
IF NOT EXISTS (SELECT 1 FROM Rooms WHERE SpecialGuestRoomHotelID IS NOT NULL AND HotelId = @HotelId)
    UPDATE Rooms SET SpecialGuestRoomHotelID = @HotelId WHERE Id = @RoomId