2017-02-27 23 views
0
ALTER PROCEDURE MyProcName 
    @IsMatch varchar(50) 
AS 
    SELECT 
     IMS_PolicyNumber, Rater_PolicyNumber 
    FROM 
     tblPolicies 
    WHERE 
     (@IsMatch = 'No Match' AND Rater_PolicyNumber <> IMS_PolicyNumber OR Rater_PolicyNumber IS NULL) -- returns No Match records 
     OR (@IsMatch = 'Match' AND Rater_PolicyNumber = IMS_PolicyNumber) --Returns Matching Records 
     OR (@IsMatch = 'Both') --Returns both: matching and no matching records 

但現在我想添加通配符參數@Rater_PolicyNumber這樣用戶就可以只需輸入前幾個字母的Rater_PolicyNumber和過濾結果,或者如果用戶留空,那麼就忽略此參數:如何使用通配符參數和其他參數過濾數據?

AND @Rater_PolicyNumber LIKE COALESCE('%'+ @Rater_PolicyNumber+'%','') 

但我有一個很難得到它與@IsMatch參數一起工作:

,如果我在@Rater_PolicyNumber傳遞值以下的作品,但如果我留空白 - 它返回的所有記錄,而不僅僅是非匹配記錄。

WHERE 
    ((@IsMatch = 'No Match' AND Rater_PolicyNumber <> IMS_PolicyNumber OR Rater_PolicyNumber is null) 
    OR Rater_PolicyNumber LIKE COALESCE('%'+ @Rater_PolicyNumber+'%','')) 

我怎樣才能返回「不匹配」,「匹配」和「都」記錄,也@Rater_PolicyNumber值過濾它們只有當用戶輸入。

感謝

回答

1

它可能很麻煩多andor工作。我已經應用了一些格式並在各節中添加了圓括號,以便在最初返回記錄時返回記錄,但是如果@Rater_PolicyNumber不爲null,它也將應用like

select IMS_PolicyNumber 
    , Rater_PolicyNumber 
from tblPolicies 
where (
     Rater_PolicyNumber like '%'+ @Rater_PolicyNumber+'%' 
     or Rater_PolicyNumber is null 
     or @Rater_PolicyNumber is null 
    ) 
    and (
     (@IsMatch = 'No Match' 
     and (Rater_PolicyNumber<>IMS_PolicyNumber 
       or Rater_PolicyNumber is null) 
     ) 
     -- returns No Match records 
     or (@IsMatch= 'Match' and Rater_PolicyNumber=IMS_PolicyNumber) 
     -- Returns Matching Records 
     or (@IsMatch = 'Both') 
     --Returns both: matching and no matching records 
    ) 
+0

謝謝。它工作,但它不返回NULL值,如果'Rater_PolicyNumber = NULL',我也需要這些。你認爲它有可能嗎? – Oleg

+0

@Oleg在第一組標準中更新爲包含'或Rater_PolicyNumber爲null' – SqlZim

+0

非常感謝!完美的作品!抱歉耽擱了!! – Oleg

0

你可以試試嗎?

 SELECT 
      IMS_PolicyNumber, Rater_PolicyNumber 
     FROM 
      tblPolicies 
     WHERE CHARINDEX(@IsMatch,CASE WHEN Rater_PolicyNumber = IMS_PolicyNumber THEN 'Match,Both' ELSE 'No MATCH,Both' END)>0