DECLARE @Jml_Terbit FLOAT 
DECLARE @Jml_Diskon FLOAT 
DECLARE @Jml_Total FLOAT 
DECLARE @Jml_Adjust FLOAT 
DECLARE @Jml_Lunas FLOAT 
DECLARE @Saldo FLOAT 
DECLARE @Tipe SMALLINT 


DECLARE @no_ref VARCHAR(11)

DECLARE list_cursor CURSOR FOR  
SELECT
	No_Ref,
	Tipe,
	Jml_Terbit,
	Diskon,
	Jml_Lunas,
	Jml_Adjust
FROM
	dbo.Note_Terbit_Master
WHERE
  No_Ref IN ('2015.089336','2015.089812','2015.090044')

OPEN list_cursor  
FETCH NEXT FROM list_cursor INTO @no_ref, @Tipe, @Jml_Terbit, @Jml_Diskon, @Jml_Lunas, @Jml_Adjust

WHILE @@FETCH_STATUS = 0  
BEGIN  
    SET @Jml_Lunas = 0	
    IF EXISTS ( SELECT
                  *
                FROM
                  dbo.Note_Lunas_Master
                WHERE
                  No_Ref = @no_ref
               ) 
       SELECT
        @Jml_Lunas = SUM(dbo.Note_Lunas_Master.Jumlah)
       FROM
        dbo.Note_Lunas_Master
       WHERE
        (dbo.Note_Lunas_Master.No_Ref = @no_ref)

    SET @Saldo = @Tipe * (ISNULL(@Jml_Terbit, 0) - ISNULL(@Jml_Diskon, 0) - ISNULL(@Jml_Lunas, 0) + ISNULL(@Jml_Adjust, 0))
    SET @Jml_Terbit = @Tipe * @Jml_Terbit
    
    SELECT
      @no_ref AS 'No_Ref',
      @Tipe AS Tipe,
      @Jml_Terbit AS Jml_Terbit,
      @Jml_Diskon AS Jml_Diskon,
      @Jml_Lunas AS Jml_Lunas,
      @Jml_Adjust AS Jml_Adjust,
      @Saldo AS Saldo

  FETCH NEXT FROM list_cursor INTO @no_ref, @Tipe, @Jml_Terbit, @Jml_Diskon, @Jml_Lunas, @Jml_Adjust
END  

CLOSE list_cursor  
DEALLOCATE list_cursor 
