Question

I have a table which contains strings which is needed to be searched [like below image]

search table TableA

After that, I have a table which stores data [like below image]

enter image description here TableB

And what the search function does is to select from TableB only if the record contains the string in TableA [i.e. The expected result should be like below image(TableC)]

enter image description here TableC

I've tried using the SQL below, but the SQL had some error while trying to run [Incorrect syntax near 'select'] , also, the SQL is a bit complicated, is there any way to make the SQL simplier?

select * from TableB a 
where exists 
    (select colA from TableB b 
        where b.colA = a.ColA and Contains (b.ColA, select searchCol from TableA))
Was it helpful?

Solution

Please try:

select 
  a.* 
From tblA a inner join tblB b 
    on b.Col like '%'+a.Col+'%'

SQL Fiddle Demo

OTHER TIPS

One of these should work according to me

SELECT b.colA 
FROM TableB b join TableA a
WHERE colA like '%' + a.ColA + '%';


SELECT b.colA
FROM TableB b join TableA a
WHERE INSTR(b.colA, '{' + a.colA + '}') > 0;
SELECT b.* FROM tblA a,tblB b
WHERE PATINDEX('%'+a.Col+'%',b.Col)>0

SQL FIDDLE DEMO

I have searched for performance difference between PATINDEX and LIKE but not got a conclusive answer , some say PATINDEX is faster when indexing can't be used which is when pattern to be searched is enclosed within wildcard character eg '%'+a.Col+'%' while other post mention they can similar performance .

Perhaps some SO SQL Wizard can look in crystal ball and show us the light

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top