Key lessons learned:
- Never use a cursor FOR loop to fetch a single row.
- Never use an explicit cursor to fetch a single row.
- Avoid writing code that hides bugs.
- User-defined functions executed inside a SQL statement should never contain their own SQL statements.
- Keep user interface and report formatting logic separate from data retrieval and business rule logic.