CREATE FUNCTION [dbo].[LESS_Mojodi_Drug]  (@id numeric(18,0))
RETURNS
@MOJODI TABLE
   (
   A_Code  varchar(4),
   K_Code  varchar(15),
   Name1 nvarchar(50), 
   Req_pos      Real,
   Reg_Fac      Real,
   Mojodi       Real, 
   kasry        Real
   )
AS  
BEGIN 
   INSERT @MOJODI
   SELECT  TmpDrugHavaleh.Sender, TmpDrugHavaleh.K_Code, KalaId.Name1, Isnull(LessKala.Tedad,0) Tedad, SUM(TmpDrugHavaleh.K_Qty1) AS K_Qty1,  Anbar.Mojodi,
   Mojodi - (Isnull(LessKala.Tedad,0) + SUM(TmpDrugHavaleh.K_Qty1)) Kasri
   FROM  TmpDrugH INNER JOIN TmpDrugHavaleh ON TmpDrugH.Id_Havaleh = TmpDrugHavaleh.Id_Havaleh 
   INNER JOIN KalaId ON TmpDrugHavaleh.K_Code = KalaId.K_Code INNER JOIN
   Anbar ON TmpDrugHavaleh.Sender = Anbar.A_Code AND TmpDrugHavaleh.K_Code = Anbar.K_Code FULL OUTER JOIN
   LessKala ON TmpDrugHavaleh.K_Code = LessKala.K_Code
   WHERE(TmpDrugH.kind_Save <> '2') And TmpDrugHavaleh.Status <> '8'
   GROUP BY TmpDrugH.Id_Havaleh, LessKala.Tedad, TmpDrugHavaleh.Sender, KalaId.Name1, TmpDrugHavaleh.K_Code,  Anbar.Mojodi,
   TmpDrugHavaleh.CtrMojodi HAVING  (TmpDrugH.Id_Havaleh = @id) 
   And Len(Sender) = 3 And Mojodi - (Isnull(LessKala.Tedad,0) + SUM(TmpDrugHavaleh.K_Qty1)) < 0
   And TmpDrugHavaleh.CtrMojodi = '1'
RETURN
END
