--create stored procedure
create procedure dbo.calc_tdyj as
begin
--declare table @res for calculated result
declare @res table(
shopname varchar(50),
yjsj varchar(50),
xm varchar(50),
zw varchar(50),
bm varchar(50),
ssld varchar(50),
gryj varchar(50),
tdyj varchar(50));
--declare cursor
declare @per varchar(50);
declare csr cursor scroll
for select distinct ssld from employees where ssld is not null;
open csr;
fetch next from csr into @per
while(@@FETCH_STATUS =0)
begin
begin
with cte as(
select xm,zw,ssld,gryj
from employees
where ssld =@per
union all
select b.xm,b.zw,b.ssld,b.gryj
from cte a
join employees b on a.xm =b.ssld)
--insert the result of calculated tdyj
insert into @res(shopname,yjsj,xm,zw,bm,ssld,gryj,tdyj)
select shopname,yjsj,xm,zw,bm,ssld,gryj,(select sum(gryj) from cte) as tdyj
from employees
where xm =@per;
end
fetch next from csr into @per
end
close csr;
deallocate csr;
--show the result
select * from @res;
end;
--calling stored procedure
exec calc_tdyj;