[整理分享技巧2] 利用sp_OA系列存儲過程,處理數學公式結果

USE Tempdb

go

IF OBJECT_ID('Tab1') IS NOT NULL

DROP TABLE Tab1

go

create table Tab1(Col1 real,formula varchar(50))

insert into Tab1 select 1000,'+20.5×÷.1'

insert into Tab1 select 50 ,'÷.5×+23.0'

insert into Tab1 select -50,'+100+(23.0×)'

go

IF OBJECT_ID('Roy_OA') IS NOT NULL

DROP function Roy_OA

go

create function Roy_OA(

@str varchar(1000)-- 要计算的表达式

)returns sql_variant

as

begin

declare @re sql_variant

declare @err int,@src varchar(255),@desc varchar(255)

declare @obj int

exec @err=sp_oacreate'MSScriptControl.ScriptControl',@obj out

if @err<>0 goto lb_err

exec @err=sp_oasetproperty@obj,'Language','vbscript'

if @err<>0 goto lb_err

exec @err=sp_oamethod@obj,'Eval',@re out,@str

if @err=0 return(@re)

lb_err:

exec sp_oageterrorinfo NULL,@src out, @descout

declare @errb varbinary(4),@s varchar(20)

set @errb=cast(@err as varbinary(4))

return(N'错误源: '+@src+char(13)+N'错误描述: '+@desc)

end

go

select

Col1,

formula,

dbo.Roy_OA(cast(Col1 as varchar)+replace(replace(formula,'×','*'),'÷','/')) as Result

from Tab1

/*

Col1 formula Result

1000 +20.5×÷.1 1023.47328244275

50 ÷.5×+23.0 2023

-50 +100+(23.0×) 188

*/

你可能感兴趣的:(分享)