关于T-SQL中的If Else

时间:2013-08-21 16:38:42

标签: tsql

SELECT NM1.nm101,
    CLP.Segment_GUID as CLPSegmentGuid,
    CASE NM1.nm101
    WHEN 'QC' THEN 'Patient'
        WHEN 'IL' THEN 'Insured'
        WHEN '74' THEN 'Corrected'
        WHEN '82' THEN 'Crossover'
    END As type,
    NM1.NM102 As Entity_Type_Qualifier,
    NM1.NM103 As Entity_Last_Name,
    NM1.NM104 As Entity_First_Name,
    NM1.NM105 As Entity_Middle_Name,
    NM1.NM108 As Entity_Identification_Code_Type,
    NM1.NM109 As Entity_Identification_Code
FROM X12_NM1 As NM1 
    INNER JOIN X12_CLP As CLP
      ON CLP.segment_guid = NM1.parent_segment_guid and NM1.Loop_Id  ='2100'

这里if nm1.nm108 = MI然后我想要那些MI的结果集。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,那么您正在查找仅存在nm1.nm108 = 'MI'的记录,否则您希望排除这些记录

尝试这样的事情

 IF EXISTS(SELECT 1 FROM X12_NM1 As NM1 
                    INNER JOIN X12_CLP As CLP 
                       ON CLP.segment_guid = NM1.parent_segment_guid
                       AND NM1.Loop_Id  ='2100'
                    WHERE nm1.nm108 = 'MI')
 BEGIN
 SELECT NM1.nm101,
 CLP.Segment_GUID as CLPSegmentGuid
 , CASE NM1.nm101
      WHEN 'QC' THEN 'Patient'
     WHEN 'IL' THEN 'Insured'
     WHEN '74' THEN 'Corrected'
     WHEN '82' THEN 'Crossover'
   END As type       
 , NM1.NM102 As Entity_Type_Qualifier
 , NM1.NM103 As Entity_Last_Name
 , NM1.NM104 As Entity_First_Name
 , NM1.NM105 As Entity_Middle_Name
 , NM1.NM108 As Entity_Identification_Code_Type
 , NM1.NM109 As Entity_Identification_Code
  FROM   X12_NM1 As NM1 
 INNER JOIN X12_CLP As CLP
    ON CLP.segment_guid = NM1.parent_segment_guid
    AND NM1.Loop_Id  ='2100'
 WHERE nm1.nm108 = 'MI'
 END
 ELSE
 BEGIN
 SELECT NM1.nm101,
 CLP.Segment_GUID as CLPSegmentGuid
 , CASE NM1.nm101
      WHEN 'QC' THEN 'Patient'
     WHEN 'IL' THEN 'Insured'
     WHEN '74' THEN 'Corrected'
     WHEN '82' THEN 'Crossover'
   END As type       
 , NM1.NM102 As Entity_Type_Qualifier
 , NM1.NM103 As Entity_Last_Name
 , NM1.NM104 As Entity_First_Name
 , NM1.NM105 As Entity_Middle_Name
 , NM1.NM108 As Entity_Identification_Code_Type
 , NM1.NM109 As Entity_Identification_Code
  FROM   X12_NM1 As NM1 
 INNER JOIN X12_CLP As CLP
    ON CLP.segment_guid = NM1.parent_segment_guid
    AND NM1.Loop_Id  ='2100'
 WHERE nm1.nm108 <> 'MI'
 END