What not to say: Everything happens for a reason. Amorette Kitsa, @funnerthanhell explains what you should not say and then tells us what you should say:
If you feel the need to say something, say, “I am so sorry that you are going through this.” Be simple, be honest, be genuine. Don't make big, flowery speeches about a divine purpose or how transitory life is. They don't need that. They need to know that you're there for them and that you care. That's all.
Look for ways to help constructively. It might not necessarily come in the form of a casserole and a psalm. Do they need a companion and distraction during chemo treatments? Are they having trouble with transportation? Do they need help with child care? Do they need help researching financial assistance? Act intuitively, keep your eyes and ears open, and help directly, where it does the most good.
Respect their boundaries. Let them decide how much help and input they want to receive from you. It is exhausting to be sick and to be expected to gratefully receive a parade of people. The parade actually feels predatory because you get people who want to snap “last photos” with you, see you for the “last time,” and hold you hostage with religious speeches that make them feel better while you feel worse. If they don't want the hassle of dealing with anyone but immediate family, respect that. If they will see you but are running low on energy, meet with them briefly. If you were never touchy-feely with them before, don't start now unless they initiate physical contact. Follow their lead.
Don't try for the “big discussion” thing. Don't force a heart-to-heart discussion for your own benefit. A gravely ill person isn't an idiot, and he or she can sense the tone of your visit. It's better to enter conversations casually and gently. Instead of “I remember you were always ... ,” which sounds stilted and final, try pointing out something that triggers an easy conversation: “There was a little boy outside who reminded me of so-and-so. Remember when we ... ”
I guess the best way that I can put it is that they're already going through hell, and they don't need for it to be any worse than it already is.