views:

42

answers:

3

HI, how can i select the Integer that falls between a pair of ( ) begining from the right of a cell? Reason being, there might be another pair of brackets containing characters

and what if some records are w/o close brackets for some reason..

e.g. 
Period | ProgrammeName             |  
Jan    | ABC (Children) (30)       |
Feb    | Helloworld (20T (20)      |

result: 30 20

i have this script,

select Period, ProgrammeName, substring(ProgrammeName,(len(ProgrammeName) - (patindex('%(%', Reverse(ProgrammeName)))+2),(len(ProgrammeName)-1)) from Table

but it only displays 30) 20)

i have been manipulating it so that it doesn't extract ')', but can get the expected results.

+2  A: 

Your database needs normalisation.

Whatever that (30) and (20) represent should be in their own column.

Graphain
hello, yeap i'm extracting them to put in a new column. the raw data comes from excel and wish to automate the process of extraction
marilyn
Why not do the work in Excel? Probably easier.
Graphain
oh, it's because this is going to be routine uploading. removing manual extraction might be prone to errors..
marilyn
+2  A: 

Hopefully this is a migration task. You could try it with a RegEx:

http://blogs.msdn.com/b/sqlclr/archive/2005/06/29/regex.aspx

EDIT: or this blog post

http://justgeeks.blogspot.com/2008/08/adding-regular-expressions-regex-to-sql.html

Arthur
+2  A: 

Quick and dirty if you want to prep the data for normalization;

select substring(fld, patindex('%([0-9]%)', fld) + 1, len(fld) - case patindex('%([0-9]%)', fld) when 0 then 0 else patindex('%([0-9]%)', fld) + 1 end)
Alex K.
can a condition be added such that when there is no ( ), it will be 0?
marilyn
`select case when patindex('%([0-9]%)', fld)=0 then '0'else substring(fld, patindex('%([0-9]%)', fld) + 1, len(fld) - case patindex('%([0-9]%)', fld) when 0 then 0 else patindex('%([0-9]%)', fld) +1 end)end`
Alex K.
for some reason, if the record is "ABCDSS(3 (15)", how do i extract 15?
marilyn