更改表的架构以满足一些约束

时间:2016-02-19 22:40:31

标签: sql-server

给出架构:

    CREATE TABLE Trains
    (Platform INTEGER NOT NULL,
    arrival DATE NOT NULL,
    departure DATE NOT NULL,
    TrainName CHAR(255) NOT NULL,
    PRIMARY KEY (Platform , arrival ));

应该对Schema进行更改以确保2件事。

    1. Should not allow Inserts Where arrival date is greater than departure date.
    2. There should be no overlaps on a single platform. i.e., If a Train A arrives on Platform 1 on 5th and leaves on 9th No other train should be inserted with Platform 1 Arriving between 5th and 9th.

需要实施约束来解决上述两个条件。

1 个答案:

答案 0 :(得分:0)

1-您需要检查约束

ALTER TABLE Trains
ADD CONSTRAINT check1t CHECK (arrival <= departure);

2-您需要一个触发器

CREATE TRIGGER IU_Trains
ON Trains
AFTER INSERT, UPDATE
AS
BEGIN
    IF exists (select * from Trains where [Platform] = inserted.Platform and arrival between inserted.arrival and inserted.dparture)
    BEGIN
        RAISERROR ('You cannot do this :)', 16, 1);
        ROLLBACK;
    END
END;