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

思った通りに動かないようです。助言がありますか?

4

2 に答える 2

6

(漠然とした質問)

カテゴリと@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 + '%' 
于 2012-06-22T09:05:20.617 に答える
1

列の数が限られている場合は、次を使用できますcase

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

もう1つのオプションは動的SQLです。

declare @sql nvarchar(max)
set @sql = 'Select Column1 From Table Where ' + @Variable + 
    ' Like ''%'' + Column2 + ''%'''
exec (@sql)
于 2012-06-22T08:33:16.387 に答える