Link to home
Start Free TrialLog in
Avatar of wasabi3689
wasabi3689Flag for United States of America

asked on

how to do this in query

I have a query like below

query 1

select name from table1 where id=....

will return a list of name


query 2

select * from table2 where table2.id like '%query1%'

this doesn't work. How to do query 2 to return the records that match any query 1 returned???
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

>How to do query 2 to return the records that match any query 1 returned???

SELECT name
FROM Query2
WHERE id IN (SELECT id FROM Query1)

btw the attached image will help
User generated image
But a quicker way (generally) would be:

SELECT Query2.name
FROM Query2
INNER JOIN (SELECT id FROM Query1) as Temp
ON Query2.ID = Temp.ID
Avatar of wasabi3689

ASKER

this is not exact what I want. Let me clear out here


There is no relationship between query 1 and query 2. But in query 2, the field called "name" contains word from the name returned from query 1.

I want to return any records whose name field contain the word from query 1

query 1

select name from table1 where id=....

will return a list of name


query 2

select * from table2 where table2.name like '%query1%
ASKER CERTIFIED SOLUTION
Avatar of Dale Fye
Dale Fye
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hi fyed,

I have this returned

The data types varchar and varchar are incompatible in the '&' operator.
query1.FieldName is varchar(64) data type

Table2.[Name] is text data type
My experience with this aspect of SQL Server is limited. You might be able to use either the CAST( ) or CONVERT( ) SQL functions, something like:

SELECT *
FROM Table2, Query1
WHERE Cast(Table2.[Name] as varchar(64)) Like '%' + query1.FieldName + '%'
the same error?

Can I convert this as procedure? I mean, have a while loop then, return each record matched. If so, how?
Please check this:
SELECT distinct T2.* FROM table1 T1 CROSS JOIN table2 T2
WHERE T2.name LIKE ('%'+T1.name+'%')

Open in new window


Also you can add the condition on id
SELECT distinct T2.* FROM table1 T1 CROSS JOIN table2 T2
WHERE T2.name LIKE ('%'+T1.name+'%')
and t1.id=..

Open in new window

select * from table2 t2
where exists
(select 1 from table1 t1
 where charindex(t1.name,t2.name) > 0);
Might need AS keyword for table aliases -
select * from table2 AS t2
where exists
(select 1 from table1 AS t1
 where charindex(t1.name,t2.name) > 0);