CREATE  FUNCTION [dbo].[Less_Exp]  (@id numeric(18,0))
RETURNS
@Exp TABLE
   (

   A_Code     varchar(5),
   K_Code     varchar(15),
   K_Qty        real,
   Exp_Date  datetime,
   Kasry         Real
   )
AS  
BEGIN 
  INSERT @Exp
    SELECT     TH.Sender, TH.K_Code, TE.K_Qty, TE.Exp_Date, TE.K_Qty - ED.K_Qty AS kasry 
    FROM        dbo.TmpExp TE  INNER JOIN
                       dbo.TmpHavaleh TH ON TE.AutoId = TH.AutoId  LEFT OUTER JOIN
                      dbo.Exp_Date ED ON TH.Sender = ED.A_Code AND TH.K_Code = ED.K_Code AND  TE.Exp_Date = ED.Exp_Date AND TE.K_Qty >= ED.K_Qty
    WHERE     (Len(TH.Sender) =3) AND (TE.K_Qty - ED.K_Qty > 0) OR
                      (Len(TH.Sender) = 3) AND (TE.K_Qty - ED.K_Qty IS NULL) AND (LEN(TH.Sender) <> LEN(TH.Reciver))  and TH.id_Havaleh=@id
RETURN
END
