Cognitive relaying has been introduced for opportunistic spectrum access systems by which a secondary node forwards primary packets whenever the primary link faces an outage condition. For spectrum sharing systems, cognitive relaying is parametrized by an interference power constraint level imposed on the transmit power of the secondary user. For sensing-based spectrum sharing, the probability of detection is also involved in packet relaying control. This paper considers the choice of these two parameters so as to maximize the secondary nodes' throughput under certain constraints. The analysis leads to a Markov decision process using dynamic programming approach. The problem is solved using value iteration. Finally, the structural properties of the resulting optimal control are highlighted.