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+'%',''))
如果用户将输入“{No>”,“匹配”和“两者”记录,并且仅按@Rater_PolicyNumber
值过滤它们,我该怎么回事。
由于
答案 0 :(得分:1)
使用多个and
和or
可能会变得棘手。我在部分周围应用了一些格式并添加了括号,以便在最初返回时返回记录,但如果@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
)
答案 1 :(得分: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