1
IF (SELECT begin_date FROM reservation WHERE id=@id) <=@end_date
AND
(SELECT end_date FROM reservation WHERE id=@id) >= @begin_date
BEGIN
    PRINT 'already reserved'
    RETURN
END

This is IF statement in my stored procedure. I have multiple reservations and I want to check if they don't intersect with the one I want to add. The problem is how to compare multiple values returned by query with variable?

10
  • You should put MIN or MAX on begin_date and end_date. May 24, 2015 at 21:33
  • But I want to compare it with all future reservations, not only one
    – Tomasz Kal
    May 24, 2015 at 21:36
  • Have you try my answer below? May 24, 2015 at 21:41
  • What is the @id and why are you using it as a parameter?
    – BICube
    May 24, 2015 at 22:09
  • @Ala That was stored procedure. So I guess, ID refers to reservation id based on user-input, and begin_date/end_date as well. May 24, 2015 at 22:15

2 Answers 2

2

If your logic for "already reserved" is correct based on your query, then this should do what you want

IF EXISTS (SELECT *
           FROM reservation rsv1
           WHERE rsv1.id=@id
             AND rsv1.begin_date <=@end_date
             AND rsv1.end_date >= @begin_date)
BEGIN
PRINT 'already reserved'
END
0
0

You should put MIN or MAX on begin_date and end_date. something like this :

IF (SELECT MIN(begin_date) FROM reservation WHERE id=@id) <=@end_date
AND
(SELECT MAX(end_date) FROM reservation WHERE id=@id) >= @begin_date
BEGIN
    PRINT 'already reserved'
    RETURN
END
1
  • What if it is okay to book a time between the beginning of the first event and the end of the last event already stored in the database?
    – BICube
    May 24, 2015 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.