sql server 实现遍历每条记录,并实现相应的业务逻辑的样例。
drop table if exists #tbTemp;
create table #tbTemp (keyId int identity, BudgetChildCode varchar(100),Amount money,Reserve money);
drop table if exists #tbSumTemp;
create table #tbSumTemp (budgeid varchar(100),PUseOfAmt money,PTakeUpAmt money);
with myTEMP AS(
select * from[BudgetYearRelease] where FinancialYearCode = '02386692-404c-4396-9968-e161c418134d' and
ParentCode = '0-0' AND del_flag = '0'
)
insert into #tbTemp SELECT BudgetChildCode,Amount,Reserve FROM myTEMP
declare @i int , @imax int , @bugetid varchar(100)
set @i = 1
select @imax = max(keyId) from #tbTemp
while @i <= @imax
begin
set @bugetid = (select top 1 BudgetChildCode from #tbTemp where keyId =@i);
--求和子级预算池的使用金额,占用金额
WITH TEMP AS
(
SELECT* FROM (select* from [BudgetYearRelease] where FinancialYearCode= '02386692-404c-4396-9968-e161c418134d') AS A WHERE BudgetChildCode = @bugetid--表的主键ID
UNION ALL
SELECT T0.* FROM TEMP,(select * from[BudgetYearRelease] where FinancialYearCode = '02386692-404c-4396-9968-e161c418134d') AS T0 WHERE TEMP.BudgetChildCode = T0.ParentCode--子级ID == 父级ID
)
insert into #tbSumTemp
SELECT @bugetid, sum(UseOfAmt) PUseOfAmt,sum(TakeUpAmt) PTakeUpAmt FROM TEMP
set @i = @i + 1
end
select
tb1.BudgetChildCode,--预算池Id
BudgetChildName,--预算池名称
tb2.PUseOfAmt,--使用金额
tb2.PTakeUpAmt,--占用金额
(tb1.Amount - tb1.Reserve - tb2.PUseOfAmt - tb2.PTakeUpAmt) as PAvailableAmt,--可用余额
(case when isnull(tb1.IsLastLevel, 'N') = 'Y' then 'true' else 'false' end) as IsLastLevel --是否最末级
from
(
select * from[BudgetYearRelease] where FinancialYearCode = '02386692-404c-4396-9968-e161c418134d'
) tb1
inner join #tbSumTemp tb2
on tb1.BudgetChildCode = tb2.budgeid