在参数变量上使用Like?

时间:2012-06-22 08:22:52

标签: sql sql-server-2008 tsql

Select Column1 From Table Where @Variable Like '%' + Column2 + '%'

我认为它似乎不起作用。有什么建议吗?

2 个答案:

答案 0 :(得分:6)

(模糊的问题)

你是否以错误的方式获得了Category和@Variable: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 + '%' 

答案 1 :(得分:1)

如果您的列数有限,则可以使用case

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

另一个选项是动态SQL:

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