搜索数据库以获取日期

时间:2013-07-25 10:21:47

标签: asp.net sql sql-server

我有这个选择声明:

SELECT *
FROM Room
LEFT JOIN booking ON (Room.RoomId = booking.RoomId)
WHERE booking.Roomid is null
  AND GETDATE() BETWEEN bookin.checkindate '" + TxtCheckIn.Text + "'
                AND booking.checkoutdate  '" + TxtCheckOut.Text + "'" + "
ORDER BY Room.RoomType

我想在预订表中查看日期是否与用户选择的登记和结帐日期相符。如果它不匹配,查询应该显示房间表中的所有房间(即使它在预订表中),只要它们有不同的日期。

1 个答案:

答案 0 :(得分:0)

您需要确定是否有任何行符合日期的条件。为此,以下查询将日期条件移动到on子句中。然后它使用窗口函数count()来计算匹配数。如果没有,则返回所有行。否则,只返回匹配。

select t.*
from (SELECT *, count(booking.RoomId) over () as numMatches
      FROM Room LEFT JOIN
           booking
           ON Room.RoomId = booking.RoomId and
              GETDATE() BETWEEN booking.checkindate '" + TxtCheckIn.Text + "' and
                                booking.checkoutdate  '" + TxtCheckOut.Text + "'" + "
     ) t
where numMatches > 0 and RoomId is not null or numMatches = 0
ORDER BY Room.RoomType