【问题标题】:How to filter data using wildcard parameter along with other parameters?如何使用通配符参数和其他参数过滤数据?
【发布时间】:2017-02-27 19:59:56
【问题描述】:
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 值过滤它们。

谢谢

【问题讨论】:

    标签: sql-server reporting-services wildcard


    【解决方案1】:

    使用多个andor 可能会变得很棘手。我已经应用了一些格式并在这些部分周围添加了括号以返回最初返回的记录,但如果@Rater_PolicyNumber 不为空,它也会应用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 
          )
    

    【讨论】:

    • 谢谢。它可以工作,但如果Rater_PolicyNumber = NULL 并且我也需要这些值,它不会返回 NULL 值。你觉得有可能吗?
    • @Oleg 更新后将or Rater_PolicyNumber is null 包含在第一组标准中
    • 非常感谢!完美运行!抱歉耽搁了!
    • @Oleg 乐于助人!
    【解决方案2】:

    你可以试试这个吗?

            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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2023-04-04
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多