Click here to Skip to main content
15,904,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a query
SQL
Select * from CityTable where CountryId="somevalue" and CityName LIKE '%andhra%'
.

Instead of this i would like to use the output of a subquery to like claues

SQL
Select * from CityTable where CountryId="somevalue" and CityName LIKE '%
 here I want to use  a query(select cityname from Allcity where CityID='1')%'.


How can I use.
Posted
Updated 30-Jul-12 20:59pm
v2

Hi,
Try this:
SQL
SELECT * FROM CityTable
WHERE CountryId="IND" 
AND CityName LIKE
'%'+(SELECT CityName FROM Allcity WHERE CityID='1')+'%'


--Amit
 
Share this answer
 
Hi Velkumar Kannan,

If your subquery returns single value you can use this query

SQL
Select * from CityTable where CountryId="somevalue" and 
CityName like '%'+ (select cityname from Allcity where CityID='1')+ '%'
 
Share this answer
 
Comments
Pablo Aliskevicius 31-Jul-12 7:37am    
NO YOU CANT!
If the subquery returns AT MOST one record, it may return zero records, which would generate an error.
If you know (in client code) that one and only one record will be returned, you also know the name of the city.
Best wishes,
Pablo.
SQL
Select * from CityTable 
where CountryId="somevalue" 
and CityName LIKE '%' + (select max(cityname) from Allcity where CityID='1') + '%'

The LIKE operator receives an expression, not necesarily a hard-coded constant.

Hope this helps,
Pablo.
 
Share this answer
 
Comments
_Amy 31-Jul-12 6:59am    
max(cityname) strange.. It'll return the value whose ASCII value will be maximum..
Pablo Aliskevicius 31-Jul-12 7:34am    
If the subquery returns multiple rows, or zero rows, you're in a pickle. Using max() lets SQL Server know that there will be one and only one result.
If there are zero rows, max() will return null, which stays null after concatenation, and the outer query will return zero rows.
Otherwise, LIKE '%' + (zero rows) + '%' will generate an error.
_Amy 31-Jul-12 7:37am    
Good logic. :) I din't downvoted..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900