Link to home
Create AccountLog in
Avatar of lexo
lexo

asked on

Query Column LIKE column from anther table.

How can I query one column like another column.
Something like this...
I've tried declaring a variable but it doesnt like my select statement.

Select *
From Table T
inner Join Table2 T2
on T.ID = T2.ID
Where T.Col1 like % T2.Col1 %
Avatar of ptjcb
ptjcb
Flag of United States of America image

Select *
From Table T
inner Join Table2 T2
on T.ID = T2.ID
Where T.Col1 like ' T2.Col1 %'


Don't use the % wildcard at the beginning of the pattern unless you do not know the first part. It makes SQL Server check every column to find a match.
ASKER CERTIFIED SOLUTION
Avatar of hongjun
hongjun
Flag of Singapore image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of lexo
lexo

ASKER

That works...kind of.
Say if the string 'testphrase' is the value of T2.Col1, how do I make a match if T.Col1 = 'hello the phrase testphrase is burried in the value of this column'
In this case, it is more of the other way round!

Select *
From Table T
inner Join Table2 T2
on T.ID = T2.ID
Where T2.Col1 like '%' + T.Col1 + '%'


OR

-- But I reckon it will be slow
Select *
From Table T
inner Join Table2 T2
on T.ID = T2.ID
Where (T2.Col1 like '%' + T.Col1 + '%') Or (T2.Col1 like '%' + T.Col1 + '%')