dbo.fn_ms_auto_supply_production

Description

Properties

Name Value
ANSI Nulls ON

True

Quoted Identifier ON

True

Encrypted

False

Execute As
Null on Null Input

False

Schema Bound

False

Assembly

Parameters

Name Data Type Length Description
@ms_item_id bigint 8
@mode_supply int 4
@max_date date 3
@quantity decimal 17

SQL Script

SET QUOTED_IDENTIFIER, ANSI_NULLS ON
GO

CREATE FUNCTION dbo.fn_ms_auto_supply_production( 
  @ms_item_id bigint
, @mode_supply int --0=FIFO --1=LIFO
, @max_date date
, @quantity decimal(38,5)
)  

RETURNS  @mutasi TABLE (
     ms_in_item_detail_id bigint 
   , receive_date date
   , quantity decimal(38,5) 
   , sum_qty decimal(38,5) 
  )  
WITH EXECUTE AS CALLER 
AS
BEGIN   


declare @sta_end_date date 
SELECT        TOP (1) @sta_end_date=end_date
FROM            dt_ms_cost_final_avg
WHERE        (ms_cost_final_avg_id = 0)


if @mode_supply=0 
begin
 
;with data_in(urut 
   , ms_in_item_detail_id   
   , receive_date  
   , quantity 
   , sum_qty  
   )
AS ( 
 SELECT        
  row_number() OVER (ORDER BY (SELECT 0))
 , ms_in_item_detail_id
 , receive_date
 , quantity_sisa        
 , SUM(quantity_sisa) OVER ( ORDER BY receive_date rows between unbounded preceding and current row ) AS TopBorcT 
 FROM            vw_ms_item_in_detail
 WHERE        (ms_item_id = @ms_item_id) AND (receive_date <= @max_date)
 and (status_id = 1) 
 and (quantity_sisa>0)
 and ( (mode_source=1 and  receive_date<=@sta_end_date) or (not(mode_source=1) and  receive_date>@sta_end_date))

 ) 
 insert into @mutasi
 select  a.ms_in_item_detail_id   
    , a.receive_date  
    , case when  a.sum_qty > @quantity then  a.quantity -(a.sum_qty -@quantity)  else a.quantity   end as pakai 
     , a.sum_qty
     from data_in as a
 where a.urut <=(select top 1 b.urut  from data_in as b  where b.sum_qty >=@quantity )

end
else
begin
 
;with data_in(urut 
   , ms_in_item_detail_id   
   , receive_date  
   , quantity 
   , sum_qty  
   )
AS ( 
 SELECT        
  row_number() OVER (ORDER BY (SELECT 0))
 , ms_in_item_detail_id
 , receive_date
 , quantity_sisa      
   
 , SUM(quantity_sisa) OVER ( ORDER BY receive_date desc , ms_in_item_detail_id desc  rows between unbounded preceding and current row ) AS TopBorcT 
 FROM            vw_ms_item_in_detail
 WHERE        (ms_item_id = @ms_item_id) AND (receive_date <= @max_date)
 and (status_id = 1) 
 and (quantity_sisa>0)
 and ( (mode_source=1 and  receive_date<=@sta_end_date) or (not(mode_source=1) and  receive_date>@sta_end_date))
 ) 
  insert into @mutasi
  select   a.ms_in_item_detail_id   
    , a.receive_date  
    , case when  a.sum_qty > @quantity then  a.quantity -(a.sum_qty -@quantity)  else a.quantity   end as pakai 
     , a.sum_qty
     from data_in as a
 where a.urut <=(select top 1 b.urut  from data_in as b  where b.sum_qty >=@quantity )



end
  
 RETURN;

end; 


GO