Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在参数变量上使用Like?_Sql_Sql Server 2008_Tsql - Fatal编程技术网

Sql 在参数变量上使用Like?

Sql 在参数变量上使用Like?,sql,sql-server-2008,tsql,Sql,Sql Server 2008,Tsql,似乎不像我想象的那样有效。有什么建议吗?如果列数有限,可以使用case: Select Column1 From Table Where @Variable Like '%' + Column2 + '%' 另一个选项是动态SQL: where case when @Variable = 'col1' then col1 when @Variable = 'col2' then col2 when @Variable = 'col3' then

似乎不像我想象的那样有效。有什么建议吗?

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

Select Column1 From Table Where @Variable Like '%' + Column2 + '%'
另一个选项是动态SQL:

where  case 
       when @Variable = 'col1' then col1 
       when @Variable = 'col2' then col2
       when @Variable = 'col3' then col3 
       ...
       end like '%' + Column2 + '%'
(模糊问题)

您是否将类别和@Variable四舍五入的方式弄错了:


它应该会起作用。你认为它是如何工作的?它不像
那样工作,而Column2像“%”++@Variable++'%
它不是一个交换函数。你的列、变量等中有什么?你说“不工作”是什么意思?两者是不同的比较;当然,它们不一定会有相同的结果。请给出一个具体的例子,说明你在哪里得到了一个你不希望得到的匹配(反之亦然)。好吧,既然你知道这个问题,那么请随意在下面发布你的答案。;)不幸的是,
变量
不是来自列的值,它实际上来自
参数
。所以我想我会更新问题的标题。你的第二个例子,请不要。。我想我可以先把变量放在表中。。让我试试。
declare @sql nvarchar(max)
set @sql = 'Select Column1 From Table Where ' + @Variable + 
    ' Like ''%'' + Column2 + ''%'''
exec (@sql)
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 + '%'