Refactoring and fixes for custom SQL code

An up-to-date version of changes proposed in pull request  https://github.com/nhibernate/nhibernate-core/pull/161.