• The code seems very complex and... "not SQL-like". It looks more like coding of nested function calls in a procedural 3GL. This is not really appropriate for SQL. God knows how well SQL compiler and optimiser are handling this stuff. I would recommend rewriting the code without using complex queries. It could be split onto several SQL statements in a stored procedure. Also consider poor performance due to UDF calls that disallow

    "set-like" processing.

    Sorry if this was not helpful.