Home Forums Programming General Insert query to distribute given amount RE: Insert query to distribute given amount

  • Use a number/tally table and CASE. Something like:

    INSERT INTO AllocationTable(SourceTableID, AllocatedAmount)

    SELECT [ID]

    ,CASE

    WHEN N.Number * 1000 <= S.Amount

    THEN N.Number * 1000

    ELSE S.Amount % ((N.Number - 1) * 1000)

    END

    FROM SourceTable S

    JOIN master.dbo.spt_values N

    ON S.Amount > (N.Number - 1) * 1000

    AND N.Number > 0

    AND N.[Type] = 'P'