使用@Parameter进行不同的搜索选项

时间:2018-02-27 06:02:03

标签: sql-server tsql azure-sql-database

我有以下查询按预期工作,但我需要稍微更改。

我有一个@SearchType参数,可以使用以下值之一:

  • 所有的
  • 名字
  • VerificationCode
  • IdentifierValue

根据传递的内容,它应该仅针对指定的相关选项执行查询的以下部分。

例如,如果传递FirstName,它应该仅搜索FirstName字段,但如果传递ALL,则应搜索All。

                SELECT *
                FROM #SearchWords s
                WHERE (c.FirstName LIKE CONCAT (s.Word,'%'))
                    OR (c.LastName LIKE CONCAT(s.Word,'%'))
                    OR (c.VerificationCode LIKE CONCAT(s.Word,'%'))
                    OR (CI.IdentifierValue LIKE CONCAT(s.Word,'%'))

任何人都知道如何实现这一目标?

SELECT
    C.ClientID, 
    C.FirstName,
    C.LastName,
    C.FullName, 
    C.DateOfBirth,
    CI.IdentifierValue,
    G.GenderName, 
    G.GenderIcon,
    C.VerificationCode,
    C.LastVisitDate,
    CV.VisitID,
    CS.ClientSanctionID
FROM 
    Client C
INNER JOIN LookUp.Gender G on
    C.GenderID = G.GenderID
LEFT JOIN ClientIdentifier CI on
    C.ClientID = CI.ClientID and
    IdentifierTypeID = @IdentifierTypeID
LEFT JOIN vwClientVisiting CV on
    C.ClientID = CV.ClientID
LEFT JOIN ClientSanction CS on
    C.ClientID = CS.ClientID and
    CS.IsActive = 1
WHERE
    (
        EXISTS( -- if we have words
                SELECT *
                FROM #SearchWords s
                WHERE (c.FirstName LIKE CONCAT (s.Word,'%'))
                    OR (c.LastName LIKE CONCAT(s.Word,'%'))
                    OR (c.VerificationCode LIKE CONCAT(s.Word,'%'))
                    OR (CI.IdentifierValue LIKE CONCAT(s.Word,'%'))
            )
        OR @SearchWordCount = 0 --if we don't have words
    )
    AND DateOfBirth BETWEEN ISNULL(@LowerDate,DateOfBirth) AND ISNULL(@UpperDate,DateOfBirth)

0 个答案:

没有答案