CREATE    FUNCTION [dbo].[LESS_Mojodi]  (@id numeric(18,0))
RETURNS
@MOJODI TABLE
   (
   A_Code  varchar(4),
   K_Code  varchar(15),
   Name1 nvarchar(50), 
   req_pos      real,
   Mojodi  real, 
   kasry real
   )
AS  
BEGIN 
 INSERT @MOJODI
 SELECT     dbo.TmpHavaleh.Sender, dbo.TmpHavaleh.K_Code, dbo.KalaId.Name1, SUM(dbo.TmpHavaleh.K_Qty1)  AS req_pos,
                   dbo.Anbar.Mojodi, dbo.Anbar.Mojodi - SUM(dbo.TmpHavaleh.K_Qty1) AS [kasry]
 FROM         dbo.Anbar INNER JOIN
                      dbo.TmpHavaleh ON dbo.Anbar.A_Code = dbo.TmpHavaleh.Sender AND dbo.Anbar.K_Code = dbo.TmpHavaleh.K_Code INNER JOIN
                      dbo.KalaId ON dbo.Anbar.K_Code = dbo.KalaId.K_Code
 GROUP BY dbo.TmpHavaleh.Sender, dbo.TmpHavaleh.K_Code, dbo.Anbar.Mojodi, dbo.TmpHavaleh.CtrMojodi, dbo.KalaId.Name1,
         dbo.TmpHavaleh.Id_Havaleh
 HAVING      (dbo.TmpHavaleh.CtrMojodi = '1') AND (dbo.TmpHavaleh.Id_Havaleh = @id) AND (dbo.Anbar.Mojodi - SUM(dbo.TmpHavaleh.K_Qty1) < 0) And ( Len(dbo.TmpHavaleh.Sender) =3)


RETURN
END
