It is legal - at least for physicians - in most states. My state medical license specifically includes a line authorizing the distribution of pharmaceuticals.
However, I am not aware of anyone in our system who does it. Our urgent care sites have a prescription "vending machine" in the lobby, but that is a different issue. From what I understand, it is almost never actually used.
Basically, almost every physician is going to make more money seeing an additional patient rather than dabbling in dispensing traditional prescriptions. Of course, situations like medical oncology and chemotherapy where they actually administer the medication are completely different.
Every once in a while some vendor stops by and tries to convince us of the untold fortunes we could make by dispensing prescriptions. However, it rarely makes financial sense unless you are bending/breaking the law. I am not even sure if my malpractice insurance would cover the "practice of pharmacy." Plus, I would not want to get rid of the safety factor that review by a pharmacist provides. In the "olden days" we would "dispense" blister packs of medication in the ED when the pharmacies were closed. However, now in most areas there is at least one 24 hour pharmacy, so most places have very gratefully stopped doing even that.
So, yes, it can legally be done - at least in some states. However, it rarely makes good business sense.