0

好的,我需要一些关于存储过程的帮助,这有点过头了,我不知道如何继续。SP 用于我正在处理的项目中的搜索功能。它是根据最终用户的选择找到可用的座位。用户应该能够根据以下内容进行搜索:

出发机场(或“任何”)

到达机场(或“任何”)

最早出发时间

最晚发车时间

提供最少座位

最多返航航班

我最初认为单独的 SELECT 语句可以解决问题,但您可能知道,选择语句被视为单独的查询,并且返回导致 6 个不同的返回。所以,我试图将它们包含在一个 SELECT 中,但我的逻辑一定很糟糕,因为返回是错误的。如果有人能指出我正确的方向,将不胜感激。代码如下:

ALTER PROCEDURE [dbo].[usp_FindSeats]
(
@DepartureAirport           char(3),
@ArrivalAirport             char(3),
@EarliestDepTime            datetime,
@LatestDepTime              datetime,
@minSeatsAvailable          int,
@maxFlightsRequested        int

 )

AS
BEGIN

SELECT * FROM Flight
WHERE
(@DepartureAirport = UPPER('ANY') OR DepartAirport = @DepartureAirport)
AND
(@ArrivalAirport = UPPER('ANY') OR ArriveAirport = @ArrivalAirport) 
AND
(DepartTime >= @EarliestDepTime) 
AND
(DepartTime <= @LatestDepTime) 
AND
(FlightSeatsAvailiable >= @minSeatsAvailable) 
AND
((SELECT COUNT(FlightID) FROM Flight) <= @maxFlightsRequested)


--IF (@DepartureAirport = UPPER('ANY')) 
--BEGIN
--(SELECT * FROM Flight WHERE DepartAirport != '')
--END
--ELSE
--SELECT * FROM Flight WHERE DepartAirport = @DepartureAirport


--IF (@ArrivalAirport = UPPER('ANY'))
--Begin
--(SELECT * FROM Flight WHERE ArriveAirport != '')
--END
--ELSE
--SELECT * FROM Flight WHERE ArriveAirport = @ArrivalAirport


--SELECT * FROM Flight WHERE DepartTime >= @EarliestDepTime

--SELECT * FROM Flight WHERE DepartTime <= @LatestDepTime

--SELECT * FROM Flight WHERE FlightSeatsAvailiable >= @minSeatsAvailable

--SELECT * FROM Flight WHERE (SELECT COUNT(FlightID) FROM Flight) <= @maxFlightsRequested
4

2 回答 2

0

尝试这个:

ALTER PROCEDURE [dbo].[usp_FindSeats]
(
    @DepartureAirport           char(3),
    @ArrivalAirport             char(3),
    @EarliestDepTime            datetime,
    @LatestDepTime              datetime,
    @minSeatsAvailable          int,
    @maxFlightsRequested        int    
 )    
AS

SELECT  TOP(@maxFlightsRequested) * 
FROM    Flight
WHERE   (@DepartureAirport = 'any' OR DepartAirport = @DepartureAirport)
        AND (@ArrivalAirport = 'any' OR ArriveAirport = @ArrivalAirport) 
        AND DepartTime >= @EarliestDepTime
        AND DepartTime <= @LatestDepTime
        AND FlightSeatsAvailiable >= @minSeatsAvailable

请注意,如果您限制返回的行数,则以某种方式对结果进行排序(ORDER BY)可能是个好主意。

于 2012-01-29T18:20:41.277 回答
0

如果我正确理解您的需求,最简单的方法是:

SELECT * FROM Flight WHERE (@DepartureAirport = UPPER('ANY') OR DepartAirport = @DepartureAirport) UNION SELECT * FROM Flight WHERE (@ArrivalAirport = UPPER('ANY') OR ArriveAirport = @ArrivalAirport) AUNION SELECT * FROM Flight WHERE ( DepartTime >= @EarliestDepTime) UNION SELECT * FROM Flight WHERE (DepartTime <= @LatestDepTime) UNION SELECT * FROM Flight WHERE (FlightSeatsAvailiable >= @minSeatsAvailable) UNION SELECT * FROM Flight WHERE ((SELECT COUNT(FlightID) FROM Flight) <= @maxFlightsRequested)

这将根据用户的输入汇总所有结果。

于 2012-01-29T18:05:26.777 回答