SQL functions to replace C++ code