自定义公式处理

数据库结构为成本表: 始重 末重 成本 续重成本 公式
1 20 10 3 (重量*2-1)续重成本+成本
20 100 8 重量
成本

录入表: 单号 重量 成本

在录入表里输入重量,自动在成本表里查询该重量处于那个重量区间,查出相应的计算公式,用sql语句计算出结果输出,求用一个存储过程写,触发器我没看明白,
---------------------------------------------------------------

--计算的存储过程
create proc p_calc
@r_code int,
@重量 int,
@结果 decimal(20,2) output
as
declare @s nvarchar(4000)
select @s='select @re='+公式+' from(select 成本='
+cast(isnull(成本,0) as varchar)+',续重成本='
+cast(isnull(续重成本,0) as varchar)+',重量='
+cast(isnull(@重量,0) as varchar)+')a'
from 成本表
where r_code=@r_code and @重量 between 始重 and 末重
exec sp_executesql @s,N'@re decimal(20,2) out',@结果 out
go

--调用示例
declare @结果 decimal(20,2)
exec p_calc 2,15,@结果 out
select 结果=@结果
go

--------------------------------------------------------------------------
--自定义公式的例子

/--说明:
根据录入的重量,从成本表中读取合适的成本计算公式
并根据此公式自动计算录入的成本值
--
/

--创建测试的成本表
create table 成本表(始重 int,末重 int,成本计算公式 varchar(100))
insert into 成本表
select 1,20,'重量2'
union all select 20,30,'重量
3'
union all select 30,40,'重量*4'
go

--创建测试的录入表
create table 录入表(id int identity(1,1),重量 int,成本 int)
go

--创建触发器,生动计算成本
create trigger t_process on 录入表
for insert,update
as
declare @s1 varchar(8000),@s2 varchar(8000),@s3 varchar(8000)
select @s1='',@s2='',@s3=''
select @s1=@s1+',@'+id+' varchar(8000)'
,@s2=@s2+'
set @'+id+'=''update 录入表 set 成本='+成本+' where id='+id+''''
,@s3=@s3+'
exec(@'+id+')'
from(
select 成本=(select 成本计算公式 from 成本表 where a.重量>=始重 and a.重量<末重)
,id=cast(id as varchar),重量=cast(重量 as varchar)
from inserted a) a
select @s1=substring(@s1,2,8000)
exec('declare '+@s1+'
'+@s2+'
'+@s3)

go

--插入数据测试
insert into 录入表(重量)
select 1
union all select 9
union all select 10
union all select 23
union all select 33
go

--显示处理结果
select * from 录入表
go

--删除测试表
drop table 成本表,录入表

/*--测试结果
id 重量 成本
----------- ----------- -----------
1 1 2
2 9 18
3 10 20
4 23 69
5 33 132

(所影响的行数为 5 行)
--*/

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus