SQL JOIN仅适用于特定的CASE

时间:2013-06-13 14:02:50

标签: sql

我有一个存储过程,我必须只在表中该记录的位字段为0的行上加入表。这可能吗?这就是我的需要

  SELECT TOP 100 
    SR.ServiceRecordID, 
    dbo.fn_ServiceRecordGetServiceName(SR.ServiceRecordID,''), 
    SR.LocationStd, 
    SR.AreaServedStd, 
    SR.RegionalLimited, 
    R.Region,
    CASE WHEN (ISNULL(R_SR.RegionID,0) = 0 AND ISNULL(R_SR_Serv.RegionID,0) = 0)
                     THEN 0 ELSE 1 END AS Visible,
    NULL
   FROM ServiceRecord SR
     INNER JOIN Sites S 
        ON SR.SiteID = S.SiteID
     INNER JOIN Regions R 
        ON R.SiteID = S.SiteID
     LEFT OUTER JOIN lkup_Region_ServiceRecord R_SR 
        ON R_SR.RegionID = R.RegionID 
           AND R_SR.ServiceRecordID = SR.ServiceRecordID
--and this is the additional join I need ONLY if RegionalLimited = 0
CASE WHEN SR.RegionalLimited = 0 THEN 
    LEFT OUTER JOIN lkup_Region_ServiceRecord_Serv R_SR_Serv 
         ON R_SR_Serv.RegionID = R.RegionID 
                        AND R_SR_Serv.ServiceRecordID = SR.ServiceRecordID 
END
WHERE SR.SiteID = @SiteID
    AND R.RegionID % 100 != 0

1 个答案:

答案 0 :(得分:1)

这应该有效

SELECT TOP 100 SR.ServiceRecordID, dbo.fn_ServiceRecordGetServiceName(SR.ServiceRecordID,''), 
SR.LocationStd, SR.AreaServedStd, 
SR.RegionalLimited, R.Region,
CASE WHEN (ISNULL(R_SR.RegionID,0) = 0 AND ISNULL(R_SR_Serv.RegionID,0) = 0) THEN 0 ELSE 1 END AS Visible,NULL
FROM ServiceRecord SR
     INNER JOIN Sites S ON SR.SiteID = S.SiteID
     INNER JOIN Regions R ON R.SiteID = S.SiteID
     LEFT OUTER JOIN lkup_Region_ServiceRecord R_SR ON R_SR.RegionID = R.RegionID 
            AND R_SR.ServiceRecordID = SR.ServiceRecordID
     LEFT OUTER JOIN lkup_Region_ServiceRecord_Serv R_SR_Serv 
             ON R_SR_Serv.RegionID = R.RegionID 
             AND R_SR_Serv.ServiceRecordID = SR.ServiceRecordID  
             AND SR.RegionalLimited = 0 -- this is the trick
WHERE SR.SiteID = @SiteID
AND R.RegionID % 100 != 0

我已将此条件AND SR.RegionalLimited = 0添加到左外连接lkup_Region_ServiceRecord