业务系统需要一个关于合同状态的报表,主要显示合同的状态,地区,合同客户类型,合同金额,利息金额等信息.
在数据库中存在4个表
crec01c,sysc01,sysc03d,crmc02分别是'合同主表','区域及业务伙伴','系统状态代码','法人信息表'
下面第一个存储过程是我第一次写的,执行时间是5秒
------------------效率较差的存储过程---------------------------
create table #tmptba --创建一个临时表,用于储存我们的结果
(
colid int identity(1,1) primary key clustered,
khlx varchar(20),
dq varchar(20),
ywhb varchar(40),
htzt varchar(20),
htbs int ,
htje numeric(13,2),
lxje numeric(13,2)
)
declare @bkhlx char(1), @ikhid int, @cywdbd char(10), @chtzt char(1), @njkje numeric(13,2), @iqx int, @nhtyll numeric(8,6) --for progress
declare @t_khlx varchar(20), @t_dq varchar(20), @t_ywhb varchar(40), @t_htzt varchar(20), @t_htbs int, @t_htje numeric(13,2), @t_lxje numeric(13,2)--for insert into #tmptba
--declare @index int
--set @index = 1
declare cur1 cursor for select bkhlx, ikhid, cywdbd, chtzt, njkje, iqx, nhtyll from crec01c
open cur1
fetch next from cur1 into @bkhlx, @ikhid, @cywdbd, @chtzt, @njkje, @iqx, @nhtyll
while @@fetch_status = 0
begin
if @bkhlx = '1'
begin
set @t_khlx = '自然人'
set @t_dq = (select vjgmc from sysc01 where cjgdm = left(@cywdbd,6))
end
else
begin
set @t_khlx = '法人'
set @t_dq = (select vjgmc from sysc01 where cjgdm = (select cbmdm from crmc02 where frid = @ikhid ) )
end
set @t_htbs = 1-- @index--合同笔数
set @t_ywhb = (select vjgmc from sysc01 where cjgdm = @cywdbd)--业务伙伴
set @t_htzt = (select vsjxc from sysc03d where czddm = 'htzt' and csjxm = @chtzt)--合同状态
set @t_htje = @njkje
set @t_lxje = @njkje * @iqx * @nhtyll * 0.001
insert into #tmptba (khlx, dq, ywhb, htzt, htbs, htje, lxje) values (@t_khlx, @t_dq, @t_ywhb, @t_htzt, @t_htbs, @t_htje, @t_lxje)
--set @index 1
fetch next from cur1 into @bkhlx, @ikhid, @cywdbd, @chtzt, @njkje, @iqx, @nhtyll
end
close cur1
deallocate cur1
select * from #tmptba
go
------------------效率较高的存储过程执行时间是1秒---------------------------
create table #tmptbl --创建一个临时表,用于储存我们的结果
(
colid int identity(1,1) primary key clustered,
khlx varchar(20),
dq varchar(20),
ywhb varchar(40),
htzt varchar(20),
htbs int ,
htje numeric(13,2),
lxje numeric(13,2)
)
insert into #tmptbl select case when a.bkhlx = '1' then '自然人' else '法人' end as khlx, dq = (select vjgmc from sysc01 where cjgdm = left(a.cywdbd,6)), ywhb = (select vjgmc from sysc01 where cjgdm = a.cywdbd), htzt = (select vsjxc from sysc03d where czddm = 'htzt' and csjxm = a.chtzt), htbs = 1, htje = a.njkje, lxje = a.njkje * a.iqx * a.nhtyll * 0.001 from crec01c a where a.bkhlx = '1'
insert into #tmptbl select case when a.bkhlx = '1' then '自然人' else '法人' end as khlx, dq = (select vjgmc from sysc01 where cjgdm = (select cbmdm from crmc02 where frid = a.ikhid)), ywhb = '无', htzt = (select vsjxc from sysc03d where czddm = 'htzt' and csjxm = a.chtzt), htbs = 1, htje = a.njkje, lxje = a.njkje * a.iqx * a.nhtyll * 0.001 from crec01c a where a.bkhlx = '2'
select * from #tmptbl
go
可以看到,第二个存储过程只用了两条sql语句就完成了第一个存储过程的工作。