If, in any of the foregoing cases, it shall appear to the court that the mortgaged premises are so situated that a sale of the whole will be most beneficial to the parties, the judgment or decree must, in the first instance, be entered for the sale of the whole premises accordingly. In such case the proceeds of such sale must be applied as well to the interest or portion or installment of the principal due as toward the whole or residue of the sum secured by such mortgage and not due and payable at the time of such sale, and if such residue do not bear interest, then the court may direct the same to be paid with a rebate of the legal interest for the time during which such residue shall not be due and payable, or the court may direct the balance of the proceeds of such sale, after paying the sum due, with costs, to be put out at interest for the benefit of the plaintiff, to be paid to him as the installments or portions of the principal or interest may become due, and the surplus for the benefit of the defendant, his representative, or assigns, to be paid to them by order of the court.
SDCL 21-47-12