SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE procedure [dbo].[p_policies_risks_incomplete_situations_data_before]
	@policies type_table_id READONLY,
	@risks type_table_id READONLY
as

SET NOCOUNT ON;

DECLARE @policies_situations type_table_id

insert INTO @policies_situations(id)
SELECT MAX(pps.pols_policy_situation_id)
FROM pol_policies_situations pps
	INNER JOIN @policies p ON p.id = pps.pols_policy_id
	INNER JOIN pol_policies pp ON pp.pol_policy_id = pps.pols_policy_id
WHERE pps.pols_policy_situation_id != pp.pol_last_policy_situation_id
GROUP BY pps.pols_policy_id

DECLARE @risks_situations type_table_id

INSERT INTO @risks_situations(id)
SELECT MAX(rrs.riss_risk_situation_id)
FROM ris_risks_situations rrs
	INNER JOIN @risks r ON r.id = rrs.riss_risk_id
	INNER JOIN ris_risks rr ON rr.ris_risk_id = rrs.riss_risk_id
WHERE rrs.riss_risk_situation_id != rr.ris_last_risk_situation_id
GROUP BY rrs.riss_risk_id 


EXEC p_policies_risks_variables_codes	@policies_situations = @policies_situations,
										@risks_situations = @risks_situations





GO
