Code :
CREATE TABLE reservation ( chambre_id int, debut datetime, fin datetime, nb_personnes int ) go CREATE UNIQUE INDEX ix_reservation ON reservation (chambre_id, debut) go CREATE TRIGGER trg_reservation_ins ON reservation instead of INSERT, UPDATE AS begin declare @nb int; declare @nbdel int; declare @chambre_id int; declare @debut datetime; declare @fin datetime; declare @nb_personnes int; SELECT @nbdel = count(*) FROM deleted; declare cur cursor FOR SELECT chambre_id, debut, fin, nb_personnes FROM inserted; open cur; fetch next FROM cur INTO @chambre_id, @debut, @fin, @nb_personnes; while @@fetch_status = 0 begin SELECT @nb = count(*) FROM reservation WHERE chambre_id = @chambre_id AND debut >= @debut AND debut < @fin; IF @nb > sign(@nbdel) begin RAISERROR('Les dates de réservation se chevauchent', 16, 1); end; else begin INSERT INTO reservation (chambre_id, debut, fin, nb_personnes) VALUES (@chambre_id, @debut, @fin, @nb_personnes); end; fetch next FROM cur INTO @chambre_id, @debut, @fin, @nb_personnes; end; close cur; deallocate cur; end; go INSERT INTO reservation VALUES (1, '2009-01-01', '2009-01-15', 1); INSERT INTO reservation VALUES (1, '2009-01-16', '2009-01-31', 2); INSERT INTO reservation VALUES (2, '2009-01-10', '2009-01-20', 1); INSERT INTO reservation VALUES (1, '2009-01-10', '2009-01-20', 1); SELECT * FROM reservation;
|