SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[p_policies_add_introducer_info]
	@policy_situation_id int,
	@return_invoices_data bit
AS
	
	SET NOCOUNT on;

	DECLARE @policy_id int

	SELECT @policy_id = pols_policy_id
	FROM pol_policies_situations pps
	WHERE		pps.pols_policy_situation_id = @policy_situation_id

	SELECT pp.*
	FROM pol_policies pp
	WHERE pp.pol_policy_id = @policy_id
		
	SELECT ppsi.*
	FROM pol_policies_situations_introducers ppsi
		INNER JOIN pol_policies_situations pps ON polsi_policy_situation_id = pols_policy_situation_id
	WHERE			pps.pols_policy_id = @policy_id
			AND ppsi.polsi_policy_situation_id = @policy_situation_id

	SELECT *
	FROM pol_policies_situations pps
	WHERE pps.pols_policy_situation_id = @policy_situation_id

	IF isnull(@return_invoices_data,0) = 1
	BEGIN 
		/*
		//ACC_INVOICES_POLICIES_VARIABLES
		//ACC_INVOICES_RISKS_VARIABLES
		//ACC_ACCOUNTS
		//ACC_INVOICES_POLICIES_VARIABLES_INTRODUCERS
		//ACC_INVOICES_RISKS_VARIABLES_INTRODUCERS
		//ACC_INVOICES
		*/
		DECLARE @invoices TABLE(invoice_id int)

		INSERT INTO @invoices(invoice_id)
		SELECT DISTINCT invpolv_invoice_id
		FROM acc_invoices_policies_variables aipv
		WHERE aipv.invpolv_policy_situation_id = @policy_situation_id

		UNION 

		SELECT invrisv_invoice_id
		FROM acc_invoices_risks_variables airv
			INNER JOIN ris_risks_situations rrs ON rrs.riss_risk_situation_id = airv.invrisv_risk_situation_id
		WHERE rrs.riss_policy_situation_id = @policy_situation_id
		

		SELECT aipv.*
		FROM acc_invoices_policies_variables aipv
			INNER JOIN @invoices i ON i.invoice_id = aipv.invpolv_invoice_id

		
		SELECT airv.*
		FROM acc_invoices_risks_variables airv
			INNER JOIN @invoices i ON i.invoice_id = airv.invrisv_invoice_id

		SELECT aa.*
		FROM vw_acc_account_clients aa
			INNER JOIN @invoices i ON i.invoice_id = aa.a_account_id

		SELECT aipvi.*
		FROM acc_invoices_policies_variables_introducers aipvi
			INNER JOIN @invoices i ON i.invoice_id = aipvi.invpolvi_invoice_id

		
		SELECT airvi.*
		FROM acc_invoices_risks_variables_introducers airvi
			INNER JOIN @invoices i ON i.invoice_id = airvi.invrisvi_invoice_id

		SELECT ai.*
		FROM acc_invoices ai
			INNER JOIN @invoices i ON i.invoice_id = ai.inv_invoice_id

		SELECT *
		FROM acc_invoices_operations
		WHERE 1 = 2



	END 

GO
