Using Like on a Parameter Variable?

后端 未结 2 1296
夕颜
夕颜 2021-01-17 01:55
Select Column1 From Table Where @Variable Like \'%\' + Column2 + \'%\'

Doesn\'t seem to work how I thought it would. Any suggestions?

2条回答
  •  情话喂你
    2021-01-17 02:29

    If you have a limited number of columns, you can use case:

    where  case 
           when @Variable = 'col1' then col1 
           when @Variable = 'col2' then col2
           when @Variable = 'col3' then col3 
           ...
           end like '%' + Column2 + '%'
    

    Another option is dynamic SQL:

    declare @sql nvarchar(max)
    set @sql = 'Select Column1 From Table Where ' + @Variable + 
        ' Like ''%'' + Column2 + ''%'''
    exec (@sql)
    

提交回复
热议问题