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

后端 未结 25 1644
灰色年华
灰色年华 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条回答
  •  悲哀的现实
    2020-11-22 03:49

    For Sql Server you can resort to Dynamic SQL.

    Most of the time in such situations you have the parameter of IN clause based on some data from database.

    The example below is a little "forced", but this can match various real cases found in legacy databases.

    Suppose you have table Persons where person names are stored in a single field PersonName as FirstName + ' ' + LastName. You need to select all persons from a list of first names, stored in field NameToSelect in table NamesToSelect, plus some additional criteria (like filtered on gender, birth date, etc)

    You can do it as follows

    -- @gender is nchar(1), @birthDate is date 
    
    declare 
      @sql nvarchar(MAX),
      @subWhere nvarchar(MAX)
      @params nvarchar(MAX)
    
    -- prepare the where sub-clause to cover LIKE IN (...)
    -- it will actually generate where clause PersonName Like 'param1%' or PersonName Like 'param2%' or ...   
    set @subWhere = STUFF(
      (
        SELECT ' OR PersonName like ''' + [NameToSelect] + '%''' 
            FROM [NamesToSelect] t FOR XML PATH('')
      ), 1, 4, '')
    
    -- create the dynamic SQL
    set @sql ='select 
          PersonName
          ,Gender
          ,BirstDate    -- and other field here         
      from [Persons]
      where 
        Gender = @gender
        AND BirthDate = @birthDate
        AND (' + @subWhere + ')'
    
    set @params = ' @gender nchar(1),
      @birthDate Date'     
    
    EXECUTE sp_executesql @sql, @params,    
      @gender,  
      @birthDate
    

提交回复
热议问题