求一个SQL函数

lsp69 2013-11-05 04:31:12
有以下数据表:
aa
3+(1*[4.000])
4*[1.000]
4*[100.000]
...
...
函数里会传入一个以上的字符串、一个运算符(+-*/)和一数字,例如:传入的运算符为:+,数字为5,那结果为:
aa
17
24
420

其实计算公式就是:
3+5+(1*[4.000+5])
4*[1.000+5]
4*[100.000+5]

例如:传入的运算符为:*,数字为0.9,那结果的公式应该为:
3+5+(1*[4.000*0.9])
4*[1.000*0.9]
4*[100.000*0.9]

其他运算符类同
...全文
204 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2013-11-06
  • 打赏
  • 举报
回复
建议用存储过程实现,

create table ls(aa varchar(30))

insert into ls
 select '3+(1*[4.000])' union all
 select '4*[1.000]' union all
 select '4*[100.000]'
 

-- 建存储过程
alter proc sp_ls(@f varchar(1),@i decimal(20,2))  
as  
begin
 select aa,aa 'aa2',cast(0 as decimal(20,2)) 'x' 
  into #t
  from ls
 
 declare @aa varchar(20),@y decimal(20,2),@tsql nvarchar(4000)
 declare ap scroll cursor for select aa from #t
 
 open ap
 fetch first from ap into @aa
 while(@@fetch_status<>-1)
 begin
  select @tsql=N'select @y='+replace(replace(@aa,']',@f+rtrim(@i)+')'),'[','(');
  exec master.dbo.sp_executesql @tsql,N'@y decimal(20,2) output',@y output;
  update #t 
    set aa2=replace(replace(@aa,']',@f+rtrim(@i)+')'),'[','('),
        x=@y
    where aa=@aa and aa2=@aa;
  fetch next from ap into @aa;
 end
 
 close ap
 deallocate ap

 select aa,aa2,x from #t
end


-- 测试1
exec sp_ls @f='+',@i=5

/*
aa                             aa2                            x
------------------------------ ------------------------------ -----------
3+(1*[4.000])                  3+(1*(4.000+5.00))             12.00
4*[1.000]                      4*(1.000+5.00)                 24.00
4*[100.000]                    4*(100.000+5.00)               420.00

(3 row(s) affected)
*/


-- 测试2
exec sp_ls @f='*',@i=0.9

/*
aa                             aa2                            x
------------------------------ ------------------------------ -----------
3+(1*[4.000])                  3+(1*(4.000*0.90))             6.60
4*[1.000]                      4*(1.000*0.90)                 3.60
4*[100.000]                    4*(100.000*0.90)               360.00

(3 row(s) affected)
*/
LongRui888 2013-11-05
  • 打赏
  • 举报
回复
引用 2 楼 lsp69 的回复:
3+(1*[4.000]) []里的值是固定格式的。 还有3+也是固定格式的
你说这个函数会传入 一个以上的字符串,这个字符串是用来什么的呢
浩方软件HFWMS 2013-11-05
  • 打赏
  • 举报
回复
3+(1*[4.000]) []里的值是固定格式的。 还有3+也是固定格式的
-狙击手- 2013-11-05
  • 打赏
  • 举报
回复
肯定是最后一个]前?

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧