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

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

5
  • It should work. How do you think it would work? Commented Jun 22, 2012 at 8:33
  • Well, It doesn't work like Where Column2 Like '%' + @Variable + '%' Commented Jun 22, 2012 at 8:37
  • It's not a commutative function. What is in your columns, variables, etc? Commented Jun 22, 2012 at 8:44
  • 1
    What do you mean, "doesn't work like" that? The two are different comparisons; naturally they won't necessarily have the same results. Show a specific example of where you get a match where you wouldn't expect one (or vice versa). Commented Jun 22, 2012 at 8:45
  • Ok, well since you know the issue, feel free to post your answer below. ;) Commented Jun 22, 2012 at 8:46

2 Answers 2

6

(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 + '%' 
Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm.. i suppose i can put the variable in a table first.. let me try.
1

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)

1 Comment

Unfortunately Variable is not a value from a column, it's actually from a param. So i guess i will update the question title. Your 2nd example, no no no, please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.