parsing - SQL Server 2005: Get first word in a varchar that matches -


i have varchar column in sql server 2005 table looks following:

mainly sunny, 13.7°c partly cloudy, 12°c, humidity 69%, wind ne 15km/h 

my goal parse out temperature values, 13.7 , 12 respectively. there series of string functions can used locate , retrieve first word in each string contains °c?

declare @t table(s varchar(255));  insert @t select 'mainly sunny, 13.7°c' union select 'partly cloudy, 12°c, humidity 69%, wind ne 15km/h';  select right(left(s, charindex('°', s)-1),    charindex(' ', reverse(left(s, charindex('°', s)-1)))-1) @t; 

so, computed column:

declare @t table (   s varchar(255),    x convert(varchar(255),right(left(s, charindex('°', s)-1),      charindex(' ', reverse(left(s, charindex('°', s)-1)))-1)) persisted );  insert @t select 'mainly sunny, 13.7°c' union select 'partly cloudy, 12°c, humidity 69%, wind ne 15km/h';  select s,x @t; 

results:

mainly sunny, 13.7°c                                  13.7 partly cloudy, 12°c, humidity 69%, wind ne 15km/h     12 

if might have strings don't contain ° symbol, then:

declare @t table (   s varchar(255),    x convert(varchar(255), case when charindex('°', s) > 0      right(left(s, charindex('°', s)-1),      charindex(' ', reverse(left(s, charindex('°', s)-1)))-1) end) persisted );  insert @t select 'mainly sunny, 13.7°c' union select 'partly cloudy, 12°c, humidity 69%, wind ne 15km/h' union select 'no weather report';  select s,x @t; 

results:

mainly sunny, 13.7°c                                  13.7 partly cloudy, 12°c, humidity 69%, wind ne 15km/h     12 no weather report                                  null 

(if want else instead of null, can't imagine what, can add else case expression.)

also, prove solution flexible without introducing performance-crippling user-defined function:

declare @searchstring varchar(8000); set @searchstring = 'km/h'; -- change '°'  declare @t table (   s varchar(255) );  insert @t select 'mainly sunny, 13.7°c' union select 'partly cloudy, 12°c, humidity 69%, wind ne 15km/h' union select 'no weather report' union select 'wind 102km/h, 23.5°c, cloudy';  select s, x = convert(varchar(255), case when charindex(@searchstring, s) > 0      right(left(s, charindex(@searchstring, s)-1),      charindex(' ', reverse(left(s, charindex(@searchstring, s)-1)))-1) end) @t; 

results:

mainly sunny, 13.7°c                                null partly cloudy, 12°c, humidity 69%, wind ne 15km/h   15 no weather report                                null wind 102km/h, 23.5°c, cloudy                 102 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -