SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[p_acc_bordereaux_delete_by_table_id]
	@table_id type_table_id READONLY
AS
	SET NOCOUNT ON;

	IF EXISTS (	SELECT	1 
				FROM	acc_bordereaux b
						INNER JOIN @table_id t ON t.id = b.bdr_bordereau_id
				WHERE	b.bdr_operation_code != 'IS')
	BEGIN
		RAISERROR ('Cannot DELETE a bordereau with an operation code != IS', 16,1) ;
		RETURN ;
	END

	DELETE	a
	FROM	acc_bordereaux_variables_commission_taxes a
			INNER JOIN @table_id t ON t.id = a.bdrvctx_bordereau_id ;
	
	DELETE	a
	FROM	acc_bordereaux_variables_taxes a
			INNER JOIN @table_id t ON t.id = a.bdrvtx_bordereau_id ;			

	DELETE	a
	FROM	acc_bordereaux_variables a
			INNER JOIN @table_id t ON t.id = a.bdrv_bordereau_id ;
			
	DELETE	a
	FROM	acc_bordereaux_products a
			INNER JOIN @table_id t ON t.id = a.bdrp_bordereau_id ;
			
	DELETE	a
	FROM	acc_bordereaux_details a
			INNER JOIN @table_id t ON t.id = a.bdrd_bordereau_id ;
			
	DELETE	abc
	FROM	dbo.acc_bordereaux_companies abc
			INNER JOIN @table_id t ON t.id = abc.bdrcie_bordereau_id ;

	DELETE	a
	FROM	acc_bordereaux a
			INNER JOIN @table_id t ON t.id = a.bdr_bordereau_id ;
			 
	DELETE	a
	FROM	acc_accounts a
			INNER JOIN @table_id t ON t.id = a.a_account_id ;
			
GO
