Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using [like] like in clause in SQL?

USE tempdb

CREATE TABLE A
(
     id INT,
     a_desc VARCHAR(100)
)

INSERT INTO A 
VALUES (1, 'vish'),(2,'hp'),(3,'IBM'),(4,'google')

SELECT * FROM A

CREATE TABLE B
(
     id INT,
     b_desc VARCHAR(100)
)

INSERT INTO B 
VALUES (1, 'IBM[SR4040][SR3939]'),(2,'hp[GR3939]')

SELECT * FROM B

SELECT * 
FROM A 
WHERE a_desc LIKE (SELECT b_desc FROM B) -- IN with LIKE problem here

all the time the ending string is not same in table B so I can't use trim approach to delete certain character and match in In clause.

-- above throwing error subquery returned more than 1 value

-- I've thousand rows in both tables just for example purpose I've created this example

--excepted output 
--IBM
--hp 

--from A table

like image 525
Vishwanath Dalvi Avatar asked Jul 05 '13 05:07

Vishwanath Dalvi


2 Answers

Try this one -

Query:

SELECT * 
FROM A
WHERE EXISTS(
    SELECT 1
    FROM B
    WHERE b_desc LIKE '%' + a_desc + '%'
)

Output:

id          a_desc
----------- ----------
2           hp
3           IBM

Execution plan:

proff

Extended statistics:

stat

Update:

SELECT A.*, B.* 
FROM A
OUTER APPLY (
     SELECT * 
     FROM B
     WHERE b_desc LIKE '%' + a_desc + '%' 
) B
WHERE b_desc IS NOT NULL
like image 122
Devart Avatar answered Sep 28 '22 11:09

Devart


you can simple join:

SELECT distinct a.* 
from A inner join b on b.b_desc like '%' + a.a_desc + '%' 
like image 21
Hiren Dhaduk Avatar answered Sep 28 '22 12:09

Hiren Dhaduk