How to use LIKE in SQL Query in where clause, but the value of LIKE will come from in other query? For example:
SELECT Code FROM TABLE1 where Code LIKE '(select top 1 Grade FROM TABLE2 WHERE Age>30)%'
Please anyone can help me
How to use LIKE in SQL Query in where clause, but the value of LIKE will come from in other query? For example:
SELECT Code FROM TABLE1 where Code LIKE '(select top 1 Grade FROM TABLE2 WHERE Age>30)%'
Please anyone can help me
I suppose your tables
create table TABLE1
(
Code varchar(50)
)
create table TABLE2
(
Grade varchar(50),
Age int
)
Adding stuffs
insert TABLE1 values ('AAE')
insert TABLE1 values ('BBM')
insert TABLE2 values ('AAE00001', 22)
insert TABLE2 values ('BBM22501', 31)
Query
select
Code
from
TABLE1 inner join TABLE2 on TABLE1.Code = LEFT(TABLE2.Grade, LEN(TABLE1.Code))
where Age > 30
Result
If it's something like that you want, be aware that it's awful. I don't help you, it's a not solution. You have to review your design.
You must concatenate the result of the subquery with the char '%'
:
SELECT Code FROM TABLE1 where Code LIKE (select top 1 Grade FROM TABLE2 WHERE Age>30) || '%'
You may change the operator ||
with +
if this is the concatenation operator of your database.
Or with the function concat()
:
SELECT Code FROM TABLE1 where Code LIKE concat((select top 1 Grade FROM TABLE2 WHERE Age>30), '%')
Note that using top 1
without order by
does not guarantee that the result will be what you would expect.
I have no idea why you would be using top
without order by
. The normal solution is to use EXISTS
:
SELECT t1.Code
FROM TABLE1 t1
WHERE EXISTS (SELECT 1
FROM table2 t2
WHERE t2.Age > 30 AND
t1.code LIKE t2.Grade + '%'
);
This assumes that +
is used for string concatenation.
I speculate that this is what you really want -- comparison to all values in table2
rather than just some indeterminate value from a matching row.