if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetImponibile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GetImponibile]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetImponibile] 
	-- Add the parameters for the stored procedure here
	@idDoc as integer
AS
	declare @iva DECIMAL 
	declare @qta DECIMAL(8,3)
	declare @prezzo DECIMAL(8,3)
	declare @totImponibile DECIMAL (8,3)
	declare @totIVA DECIMAL (8,3)
	declare @totaleDocumento DECIMAL(8,3)
BEGIN

	SET NOCOUNT ON;
	set @totImponibile = 0.0
	set @totaleDocumento = 0.0

	DECLARE Cursore CURSOR FOR 	select iva, qta, prezzoCopertina from documentirighe where iddocumento = @idDoc 
    
	OPEN Cursore

	FETCH NEXT FROM Cursore INTO @iva,@qta,@prezzo

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		 if (@iva=0)
			begin
				set @totImponibile = @totImponibile + ( @prezzo ) * @qta
			end	
		else
			begin
				--print (@prezzo / ( 1 + (@iva/100) ))
				set @totImponibile =  @totImponibile + (@prezzo / ( 1 + (@iva/100) ))   * @qta
				--print @totImponibile
			end	
		set @totaleDocumento = @totaleDocumento + ( @prezzo * @qta )

		FETCH NEXT FROM Cursore INTO @iva,@qta,@prezzo

	END

CLOSE Cursore
DEALLOCATE Cursore
--print @totaleDocumento 
--print @totImponibile

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[returnVAlues]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE dbo.returnVAlues 
( 
    totDocumento decimal (8,3),
    totImponibile decimal(8,3)
) 
INSERT dbo.returnVAlues values (@totaleDocumento , @totImponibile)

select * from dbo.returnVAlues 
drop TABLE dbo.returnVAlues 
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

