IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_update_account_branch]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_update_account_branch]
GO


CREATE proc [dbo].[mps_update_account_branch]
@bcid int,
@aiid int,
@aib_id bigint,
@aib_ownerdpid bigint,
@aib_budget bigint
as
begin
set nocount on
update mps_account_branch set
aib_ownerdpid = case when @aib_ownerdpid = '-999999999' then aib_ownerdpid else @aib_ownerdpid end,
aib_budget = case when @aib_budget = '-999999999' then aib_budget else @aib_budget end
where aib_bcid = @bcid and aib_aiid = @aiid

if @aib_budget != '-999999999'
begin
if @aib_budget = 1
begin
UPDATE a  SET aib_budget = 1 
FROM mps_account_branch a 
right JOIN 
(select * from mps_account_item where ai_faiid = @aiid) as b 
ON a.aib_bcid = @bcid and a.aib_aiid = b.ai_id 
end 

declare @count int, @level int, @faiid int;
select  @level=ai_level,@faiid=ai_faiid from mps_account_item where ai_id = @aiid
while @level> 0
begin
select @faiid=ai_faiid from mps_account_item where ai_id = @aiid
select @count=COUNT(ai_id) from mps_account_item,mps_account_branch b 
where  ai_faiid = @faiid and ai_id != @aiid and b.aib_aiid = ai_id 
 and b.aib_bcid = @bcid
if @count = 0
begin
UPDATE mps_account_branch  SET aib_budget = @aib_budget 
where aib_aiid = @faiid and aib_bcid = @bcid;
set @aiid = @faiid;
end
set @level = @level -1
end
end

set nocount off
end