Is there a combination of “LIKE” and “IN” in SQL?

后端 未结 25 1946
灰色年华
灰色年华 2020-11-22 03:08

In SQL I (sadly) often have to use \"LIKE\" conditions due to databases that violate nearly every rule of normalization. I can\'t change that right now. But tha

25条回答
  •  萌比男神i
    2020-11-22 03:54

    Sorry for dredging up an old post, but it has a lot of views. I faced a similar problem this week and came up with this pattern:

    declare @example table ( sampletext varchar( 50 ) );
    
    insert @example values 
    ( 'The quick brown fox jumped over the lazy dog.' ),
    ( 'Ask not what your country can do for you.' ),
    ( 'Cupcakes are the new hotness.' );
    
    declare @filter table ( searchtext varchar( 50 ) );
    
    insert @filter values
    ( 'lazy' ),
    ( 'hotness' ),
    ( 'cupcakes' );
    
    -- Expect to get rows 1 and 3, but no duplication from Cupcakes and Hotness
    select * 
    from @example e
    where exists ( select * from @filter f where e.sampletext like '%' + searchtext + '%' )
    

    Exists() works a little better than join, IMO, because it just tests each record in the set, but doesn't cause duplication if there are multiple matches.

提交回复
热议问题