SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW [dbo].[vw_acc_invoices_risks_variables_taxes_cies]
AS

		SELECT	i.invrisvt_invoice_id							AS invoice_id,
				i.invrisvt_risk_situation_id					AS risk_situation_id,
				i.invrisvt_variable_id							AS variable_id,
				i.invrisvt_tax_id								AS tax_id,
				isnull(pv.prdv_company_id, p.pol_company_id)	AS company_id,
				i.invrisvt_tax_value							AS tax_value
		FROM	acc_invoices_risks_variables_taxes i
				INNER JOIN ris_risks_situations ps			ON	ps.riss_risk_situation_id = i.invrisvt_risk_situation_id
				INNER JOIN pol_policies p					ON	p.pol_policy_id = ps.riss_policy_id
				INNER JOIN pr_products_variables pv			ON pv.prdv_variable_id = i.invrisvt_variable_id

		WHERE	NOT EXISTS	(
							SELECT	1
							FROM	acc_invoices_risks_variables_taxes_cies ir
							WHERE	ir.invrisvtc_invoice_id = i.invrisvt_invoice_id
							AND		ir.invrisvtc_risk_situation_id = i.invrisvt_risk_situation_id
							AND		ir.invrisvtc_variable_id = i.invrisvt_variable_id
							AND		ir.invrisvtc_tax_id = i.invrisvt_tax_id
							)

		UNION ALL

		SELECT	ir.invrisvtc_invoice_id, 
				ir.invrisvtc_risk_situation_id,
				ir.invrisvtc_variable_id,
				ir.invrisvtc_tax_id,
				ir.invrisvtc_company_id,
				ir.invrisvtc_tax_value
		FROM	acc_invoices_risks_variables_taxes_cies ir

GO
