Fix SQL function creation for tests and scenarios

Supersedes #415.
Good catch.