IF dbo.fEsisteTabella('CausaliContAgenziaEntrate') = 0 begin
CREATE TABLE [dbo].[CausaliContAgenziaEntrate](
	[IDCausaleContAgenziaEntrate] [int] IDENTITY(1,1) NOT NULL,
	[Causale_CD] [nvarchar](20) NOT NULL,
	[IDAgenziaEntrateTpDocumento] [int] NOT NULL,
 CONSTRAINT [PK_CausaliContAgenziaEntrate] PRIMARY KEY CLUSTERED 
(
	[IDCausaleContAgenziaEntrate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
end
|GO|
DECLARE @TD01 int
DECLARE @TD04 int
SELECT @TD01 = IDAgenziaEntrateTpDocumento FROM AgenziaEntrateTpDocumenti where TpDoc_Cd = 'TD01'
SELECT @TD04 = IDAgenziaEntrateTpDocumento FROM AgenziaEntrateTpDocumenti where TpDoc_Cd = 'TD04'

IF @TD01 > 0 BEGIN
	INSERT INTO CausaliContAgenziaEntrate
		select Codice, @TD01  from CausaliCont 
			WHERE
					Codice NOT IN (SELECT Causale_CD FROM CausaliContAgenziaEntrate)
				and tipo = 'Acquisto' AND SegnoIva = 0
			order by 1
	INSERT INTO CausaliContAgenziaEntrate
		select Codice, @TD01  from CausaliCont 
			WHERE
					Codice NOT IN (SELECT Causale_CD FROM CausaliContAgenziaEntrate)
				and tipo = 'Vendita' AND SegnoIva = 0
			order by 1
END

IF @TD04 > 0 BEGIN
	INSERT INTO CausaliContAgenziaEntrate
		select Codice, @TD04  from CausaliCont 
			WHERE
					Codice NOT IN (SELECT Causale_CD FROM CausaliContAgenziaEntrate)
				and tipo = 'Acquisto' AND SegnoIva = 1
			order by 1
	INSERT INTO CausaliContAgenziaEntrate
		select Codice, @TD04  from CausaliCont 
			WHERE
					Codice NOT IN (SELECT Causale_CD FROM CausaliContAgenziaEntrate)
				and tipo = 'Vendita' AND SegnoIva = 1
			order by 1
END
|GO|
