打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
中缀算术转后缀算术表达式并计算的函数

中缀算术转后缀算术表达式并计算的函数

分类: SQL函数分享系列 264人阅读 评论(0) 收藏 举报

--创建函数(原创: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),varchar(100))

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

declare  @sv table(id int identity(1,1),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,'(')>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

*/

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
实用t
ISNULL() and COALESCE()
在数据库中如何让列变成行,让行变成列的问题
用SQL语句删除重复记录的四种方法
SqlServer Split功能函数
sql server触发器自动生成编号
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服