Sounds like a possible fissure, or tear, in the rectum. Fissures can cause extremely sharp pain - like someone sticking a knife up the rectum. Sometimes it's constant pain, but other times, it may come and go, like yours. You should go to a doctor to find out for sure what's going on.
Take care!