【叶子函数分享十七】中缀算术转后缀算术表达式并计算的函数

本文介绍了一个使用SQL创建的函数,该函数能够解析并计算复杂的数学表达式字符串。通过定义临时表和变量,函数逐步解析输入字符串中的算术运算,并最终返回计算结果。

--创建函数(原创:cson_cson)

create function dbo.js(@bds varchar(1000))

returns float

as

begin

declare @i int,@j int

declare @c1 char(1),@c2 char(1),@c varchar(100)

declare @v1 float,@v2 float,@v float

declare @t table(id int identity(1,1),s varchar(100))

declare @s table(id int identity(1,1),s varchar(100))

declare @sv table(id int identity(1,1),v float)

select @i = 0,@j = len(@bds),@c2 = '',@c = ''

while @i<@j

begin

select @c1 = @c2,@i = @i+1

select @c2 = substring(@bds,@i,1)

if charindex(@c2,'.0123456789') > 0 or (@c2 = '-' and @c1 in('','*','-','+','/','('))

begin select @c = @c + @c2 continue end

if @c <> '' begin insert @t(s) select @c select @c = '' end

if charindex(@c2,')')>0

begin

insert @t(s) select s from @s where id > isnull((select max(id) from @s where s in('(')),0) order by id desc

delete @s where id >= isnull((select max(id) from @s where s in('(')),0)

continue

end

if charindex(@c2,'+-)')>0

begin

insert @t(s) select s from @s where id > isnull((select max(id) from @s where s in('(')),0) order by id desc

delete @s where id > isnull((select max(id) from @s where s in('(')),0)

if @c2 <> ')' insert @s(s) select @c2

continue

end

if charindex(@c2,'*/')>0

begin

insert @t(s) select s from @s where id > isnull((select max(id) from @s where s in('(','+','-')),0) order by id desc

delete @s where id > isnull((select max(id) from @s where s in('(','+','-')),0)

insert @s select @c2

continue

end

if charindex(@c2,'(')>0 insert @s select @c2

end

if @c <> '' insert @t(s) select @c

insert @t(s) select s from @s order by id desc

select @i = 0,@j = max(id) from @t

while @i < @j

begin

select @i = @i + 1

select @c = s from @t where id = @i

if @c = '(' continue

if @c not in('*','-','+','/') begin insert @sv(v) select convert(float,@c) continue end

select @v2 = v from @sv delete @sv where id = (select max(id) from @sv)

select @v1 = v from @sv delete @sv where id = (select max(id) from @sv)

select @v = case @c when '+' then @v1 + @v2 when '-' then @v1 - @v2

when '*' then @v1 * @v2 when '/' then @v1 / @v2 end

insert @sv(v) select @v

end

select @v = v from @sv

return @v

end

--测试示例

declare @bds varchar(100)

select @bds = '1+(2+3)*4-9'

select dbo.js(@bds) as func

--运行结果

/*

func

----------------------

12

*/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值