Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi I am having values like this i want to extract numeric and decimal values from bellow values3 RTX3.4.RTX35943.4ABC3.4 xyrExpected Output33.435943.43.4Thanks in advance
declare @a varchar(40),@start int, @end int ,@number varchar(1024), @sting varchar(1024),@var varchar(1)select @a = '12ads..235'SELECT @end = datalength(@a),@start = 1 ,@number = '',@sting = ''while ( @start <= @end)BEGINSELECT @var = substring(@a,@start,1)IF isnumeric(@var) = 1 SET @number = @number+@varELSE SET @sting = @sting + @varSELECT @start = @start+1ENDselect @number as Number ,@sting as string
xpandre
Posting Yak Master
212 Posts
Posted - 2009-03-06 : 05:00:08
[code]set nocount ondeclare @str table (a varchar(max))declare @t varchar(max)insert into @str values ('3 RTX')insert into @str values ('3.4.RTX')insert into @str values ('3594')insert into @str values ('3.4ABC')insert into @str values ('3.41 xyr')declare c1 cursor for select a from @stropen c1fetch c1 into @twhile @@fetch_status = 0beginselect cast(a as decimal(6,2)) from( select case when len(@t) - len(replace(@t,'.','')) > 1 then reverse(substring (reverse( cast(cast((select substring(@t,n,1) from (select 1 n union select 2 n union select 3 n union select 4 n union select 5 n union select 6 n union select 7 n union select 8 n union select 9 n ) as num where n <= len(@t) and substring(@t,n,1) not like '[a-z]' for xml path('')) as xml) as varchar(max))),2,len(@t))) else cast(cast((select substring(@t,n,1) from (select 1 n union select 2 n union select 3 n union select 4 n union select 5 n union select 6 n union select 7 n union select 8 n union select 9 n ) as num where n <= len(@t) and substring(@t,n,1) not like '[a-z]' for xml path('')) as xml) as varchar(max)) end a ) ffetch c1 into @tendclose c1deallocate c1set nocount off[/code]
pootle_flump
1064 Posts
Posted - 2009-03-06 : 05:15:21
Set based solution:
SET NOCOUNT ONDECLARE @str TABLE (a VARCHAR(MAX))DECLARE @t VARCHAR(MAX)INSERT INTO @str VALUES ('3 RTX')INSERT INTO @str VALUES ('3.4.RTX')INSERT INTO @str VALUES ('3594')INSERT INTO @str VALUES ('3.4ABC')INSERT INTO @str VALUES ('3.41 xyr')SELECT SUBSTRING(a, 1, COALESCE(NULLIF(PATINDEX('%[^0-9.]%', a) - CASE WHEN LEN(a) - LEN(REPLACE(a, '.', '')) >= 2 THEN 2 ELSE 1 END, -1), LEN(a)))FROM @str