Using Like on a Parameter Variable?

后端 未结 2 1294
夕颜
夕颜 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:26

    (vague question)

    Have you got Category and @Variable round the wrong way: sqlFiddle

    create table the_table 
    (
      category varchar(10),
      [Date] datetime,
      Amount decimal(12, 2)
    )
    
    insert into the_table
    values
    ( 'X', '2012-1-1', 10),
    ( 'X', '2012-1-3', 10),
    ( 'Y', '2012-1-3', 20),
    ( 'Y', '2012-1-5', 10)
    
    declare @Variable varchar(10)
    set @Variable = 'Y'
    
    Select * 
    From the_table 
    --Where @Variable Like '%' + category + '%' 
    Where category Like '%' + @Variable + '%' 
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题