在没有子查询的情况下重写sp

时间:2012-10-03 05:30:54

标签: sql join

有没有办法在没有子查询的情况下重写此SP。基本上I.RemarkId有时可以为null,我试图使用左连接或左外连接。我希望始终从flightinfo返回行,并在I.RemarkId不为空时返回备注,并在I.remarkId为空时在备注列中返回null。

ALTER PROCEDURE [dbo].[Peach_GetFlightInfoForRoute]
    @FlightDate datetime,   
    @Origin nvarchar(3),
    @dest nvarchar(3),
    @Lang nvarchar(2)
AS
SELECT 
     I.FlightNumber
    ,FlightDate
    ,STD
    ,(select [Message] FROM FlightRemarkDetail WHERE RemarkId = I.RemarkId WHERE LangCode = @Lang) As [Remark]
FROM 
     [FlightInfo] as [I]
JOIN
     [FlightNumbers] as [N]
ON  
    I.FlightNumber = N.FlightNumber 
WHERE 
    FlightDate = @FlightDate AND (@Origin='' OR @Origin = N.Origin) AND (@dest = '' OR @dest = N.Destination)

FlightInfo
===========
FlightNumber    nvarchar(16)
FlightDate  datetime    
STD nvarchar(4) 
RemarkId int NULL

FlightRemarkDetail
==================
RemarkDetailId  int 
RemarkId    int NOT NULL
LangCode    nvarchar(2) 
Message nvarchar(512)   

1 个答案:

答案 0 :(得分:1)

LEFT OUTER JOIN基本上是相同的。 LEFT OUTER JOIN使得它不需要子表具有匹配的记录。因此,如果FlightRemarkDetail中没有记录,它将只显示为null(类似于从子查询中获得的结果)。假设FlightInfo和FlightRemarkDetail之间存在1到1(或1到0)的匹配。如果每个FlightInfo存在多个FlightRemarkDetail记录,则会导致重复的行。

SELECT 
     I.FlightNumber
    ,FlightDate
    ,STD
    ,D.Message As [Remark]
FROM 
     [FlightInfo] as [I]
JOIN [FlightNumbers] as [N] ON I.FlightNumber = N.FlightNumber 
LEFT OUTER JOIN [FlightRemarkDetail] as [D] ON I.RemarkId = D.RemarkId
WHERE 
    FlightDate = @FlightDate AND (@Origin='' OR @Origin = N.Origin) AND (@dest = '' OR @dest = N.Destination)