Ver Mensaje Individual
  #4 (permalink)  
Antiguo 18/01/2011, 16:41
Avatar de royrojas
royrojas
 
Fecha de Ingreso: diciembre-2004
Mensajes: 458
Antigüedad: 19 años, 4 meses
Puntos: 3
Respuesta: Convertir Formula en Resultado

Con una funcion SPLIT se podria hacer eso que quieres.

Paso 1. Creamos la funcion Split

Código:
CREATE FUNCTION SPLIT
(
 @s nvarchar(max),
 @splitChar nchar(1)
)
returns @t table (id int identity(1,1), val nvarchar(max))
as
begin

declare @i int, @j int
select @i = 0, @j = (len(@s) - len(replace(@s,@splitChar,'')))

;with cte 
as
(
 select
  i = @i + 1,
  s = @s, 
  n = substring(@s, 0, charindex(@splitChar, @s)),
  m = substring(@s, charindex(@splitChar, @s)+1, len(@s) - charindex(@splitChar, @s))

 union all

 select 
  i = cte.i + 1,
  s = cte.m, 
  n = substring(cte.m, 0, charindex(@splitChar, cte.m)),
  m = substring(
   cte.m,
   charindex(@splitChar, cte.m) + 1,
   len(cte.m)-charindex(@splitChar, cte.m)
 )
 from cte
 where i <= @j
)
insert into @t (val)
select pieces
from 
(
 select 
 ltrim(rtrim(case when i <= @j then n else m end)) pieces
 from cte
) t
where
 len(pieces) > 0
option (maxrecursion 0)

return

end

GO
Y luego la invocas

select SUM(cast(val as decimal(10,2))) from dbo.SPLIT('54.2 + 83 + 356 + 97','+')

Si bien aqui lo hace para esta linea, lo ideal seria que la misma funcion retorne ya el valor de la suma. Entonces en ese caso solamente modificas la funcion para que en lugar de que te retorne una tabla, te retorne un decimal con el resultado.

y solamente harias algo como asi

SELECT FORMULA, dbo.SumaFormula(FORMULA) as RESULTADO from DATOS
__________________
roy rojas
Programación en Español: DotNetcr.com