CREATE FUNCTION [dbo].[LESS_Mojodi_Drug]
(
    @id NUMERIC(18, 0)
)
RETURNS @MOJODI TABLE
(
    A_Code VARCHAR(4),
    K_Code VARCHAR(15),
    Name1 NVARCHAR(100),
    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
               AND dbo.TmpDrugHavaleh.Sender = dbo.LessKala.Sender
    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(TmpDrugHavaleh.Sender) = 3
           AND Mojodi - (ISNULL(LessKala.Tedad, 0) + SUM(TmpDrugHavaleh.K_Qty1)) < 0
           AND TmpDrugHavaleh.CtrMojodi = '1';
    RETURN;
END;