SAMs are perfectly effective against ships, more so if they have special fuze mods for surface targets.Ships are larger targets than aircraft, therefore a missile needs a larger warhead if it's going to be effective at neutralizing a ship. Anti-ship missiles have larger warheads than anti-air missiles. To answer the question technically yes, an anti-air missile can hit a ship but it will not be an effective weapon.
HQ-9, for example, has a 180kg warhead. That's way more than NSM, and is neatly around the weight of a 9" shell. Even lighter SAMs (say, in HQ-16 class) still have warheads heavier than 6" shells(WW2 cruiser shell), plus the weight of all the missile itself.
Moreover, SAMs tend to come at very high speeds, adding to both kinetic energy and difficulty of intercept.