Link to home
Start Free TrialLog in
Avatar of Ludique
LudiqueFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Query to show text in string enclosed in brackets eg Nevada (USA) -> USA

My table has a list like this:

REGION
Nevada (USA)
Ontario (CAN)
Bretagne (FR)
Cornwall (UK)

I would like a query that shows results like this:
Region      Country
Nevade     USA
Ontario     CAN
Bretagne   FR
Cornwall    UK

I've experimented with various combinations of Left, Right, Mid, InStr, InStrRev, etc but just can't get the syntax right




Avatar of DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
Flag of United States of America image

Here you go:

SELECT Left(Replace(Replace([RgnCtry],"(",""),")",""),InStr(1,Replace(Replace([RgnCtry],"(",""),")","")," ")-1) AS CountryX, Mid(Replace(Replace([RgnCtry],"(",""),")",""),InStr(1,Replace(Replace([RgnCtry],"(",""),")","")," ")+1) AS RegionX
FROM tblRgn;


mx
CountryX      RegionX
Ontario      CAN
Nevada      USA
Bretagne      FR
Cornwall      UK

mx
Avatar of Ludique

ASKER

Apart from swapping RegionX and CountryX thus:

SELECT Left(Replace(Replace([Region],"(",""),")",""),InStr(1,Replace(Replace([Region],"(",""),")","")," ")-1) AS RegionX, Mid(Replace(Replace([Region],"(",""),")",""),InStr(1,Replace(Replace([Region],"(",""),")","")," ")+1) AS CountryX
FROM Regions;

Brilliant! Thank you very much.
You are welcome

Yes, I had to alias those because I used those names in a table I created.

mx
Avatar of Ludique

ASKER

Sorry, I spoke too soon

I just found out that if the Region has spaces it all goes wrong

e.g

New Mexico (USA)  comes out  
New                Mexico (USA)  instead of
New Mexico    USA
Avatar of Ludique

ASKER

Well lots I suppose.  A region name could be made up of several words.  

Wouldn't it be easier to cut it up on the parentheses rather than the spaces?
ASKER CERTIFIED SOLUTION
Avatar of DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
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
Avatar of Ludique

ASKER

That's it!

Lovely.  Looks tidy too :)
Hi,

Check out this.

SELECT	SUBSTRING(RgnCtry, 1, CHARINDEX('(',RgnCtry)-1)Country,
		SUBSTRING(RgnCtry, CHARINDEX('(',RgnCtry)+1, (CHARINDEX(')',RgnCtry)-CHARINDEX('(',RgnCtry)-1))Region

Open in new window


Sample Code

DECLARE @Input VarChar(50)

SET @Input = 'Nevada (USA)'
select CHARINDEX(')',@Input)-1

SELECT	SUBSTRING(@Input, 1, CHARINDEX('(',@Input)-1)Country,
		SUBSTRING(@Input, CHARINDEX('(',@Input)+1, (CHARINDEX(')',@Input)-CHARINDEX('(',@Input)-1))
		
		
		

 

Open in new window



- Bhavesh
Hi,

Sorry guys....

I provide solution for SQL Server....

Pls ignore... :-)