我有一个 SQL 查询,我想优化它作为 SP 的内部查询。
SELECT TOP 1 @CurrentStartDate = Strt_Dt FROM (
SELECT 1 AS seq, Stat, Strt_Dt, Est_Hrs_Comp, EndDate, Tckt_Id, Envr
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID AND stat = 'INPR'
UNION
SELECT TOP 1 2 AS seq, Stat, Strt_Dt, Est_Hrs_Comp, EndDate, Tckt_Id, Envr
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID AND stat = 'CMPL'
ORDER BY enddate DESC
UNION
SELECT TOP 1 3 AS seq, Stat, Strt_Dt, Est_Hrs_Comp, EndDate, Tckt_Id, Envr
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID AND stat = 'PLND'
ORDER BY strt_dt
UNION
SELECT 4 AS seq, 'UNP', NULL, NULL, NULL, tckt_id, 'Unplanned'
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID
) aa
ORDER BY aa.seq
有没有更好的方法来使用这个查询。我需要这个,因为我有很多具有相同类型的逻辑。