SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE procedure [dbo].[p_claim_variables_update_pay]
	@table_id type_table_id READONLY,
	@variable_id int 
as

	/*
	DGE

	MAJ des totaux règlements d'une variable 

	*/

	set nocount on;


	update	v
	set		v.clv_payment = isnull(t.mnt, 0)
	from	claim_variables v
			inner join @table_id c on c.id = v.clv_claim_id

			left join (
						select	clacc_claim_id, clacc_variable_id, mnt = SUM(abs(a.a_amount))
						from	claim_variables_accounts c
								inner join acc_accounts a on a.a_account_id = c.clacc_account_id
						where	a.a_type_code = 'CP'
						AND		c.clacc_disable_accounting = 0
						group by clacc_claim_id, clacc_variable_id	
						) as t	on	t.clacc_claim_id = v.clv_claim_id
								and	t.clacc_variable_id = v.clv_variable_id

	where	@variable_id < 0 or v.clv_variable_id = @variable_id
			
GO
