我想为以下查询在ASC中订购时间。我尝试在WHERE子句之后添加ORDER BY,但由于使用了join语句而无法获得结果。我在这里添加了完整的sql查询。
ALTER PROCEDURE [dbo].[USP_GetFlightInfo]
(
@Origin NVARCHAR(50)=null,
@Destination NVARCHAR(50)=null,
@FlightNo NVARCHAR(50)= null
)
AS
BEGIN
SET NOCOUNT ON;
IF @FlightNo IS NULL
(
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,tfSSS.DescriptionName, tfSS.FlightStatus from tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
where tfs.Origin=@Origin and tfs.Destination =@Destination
ORDER BY tfs.[Time];
)
ELSE IF @FlightNo IS NOT NULL
(
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,tfSSS.DescriptionName, tfSS.FlightStatus from tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
where tfs.Origin=@Origin and tfs.Destination =@Destination and tfs.FlightNo=@FlightNo and tfs.FlightNo =@FlightNo
ORDER BY tfs.[Time];
)
END
答案 0 :(得分:1)
只说:
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,
tfSSS.DescriptionName, tfSS.FlightStatus
FROM tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
WHERE tfs.Origin=@Origin and
tfs.Destination =@Destination and
(
tfs.FlightNo =@FlightNo or
@FlightNo is null
)
ORDER BY tfs.[Time];
作为存储过程中的代码。无需IF
并重复查询。
现有代码中的主要问题是SQL Server使用BEGIN
和END
来封装代码块-而不是括号()
。因此,IF
应该看起来像:
IF <Something>
BEGIN
--If block
END
ELSE
BEGIN
--Else block
END