How can I optimize/refactor a TSQL “LIKE” clause?

前端 未结 7 744
野的像风
野的像风 2020-12-10 04:50

I have a table with 117000 or so records. I need to perform a search that checks 3 separate fields for a given string pattern.

My where clause is as follows:

7条回答
  •  情深已故
    2020-12-10 05:20

    I tried one possible solution. Before this solution even query was not returning result and causing connection timeout error.

    My query was having date filter and other criteria. All other criteria was like search. One column keyword was searching like '%abc%' on ntext column and it was doing full table scan.

    Solution:

    Divide query in 2 parts. 1) First part in CTE (Common Table Express) 2) Apply all search criteria on CTE.

    WITH SearchData(Column1,Column2,Column3,Column4,........)
        AS
        (
        SELECT Column1,Column2,Column3,Column4,...........
        FROM myTable1 WITH(NOLOCK) 
                INNER JOIN MyTable2 WITH(NOLOCK) 
                    ON MyTable1.id = MyTable2.Id
        WHERE (MyTable1.CreationTime >= '2014-04-27' AND MyTable1.CreationTime <= '2014-05-01') 
     )
    
        SELECT DISTINCT top 250 Column1,Column2,Column3,Column4
        FROM SearchData
        WHERE   (ISNULL(Column1,'') LIKE @Column1  +'%' OR @Column1 IS NULL)
                and (Column2 LIKE @Column2+ '%' OR @Column2 IS NULL)
                ...
                ...
                ...
                ...
                AND (Column10 like '%'+@Column10+'%' or @Column10 IS NULL)
                AND @Column1+@Column2+@Column3+........@Column10 <> ''  
                ORDER BY [CreationTime] DESC
    

    It worked for me.

提交回复
热议问题