Refactored SQL output

Wrote a more general concept of SQL output -- there are a lot more
tables to do, and I was uncomfortable at how much hand-string hackery
was currently involved.

Still need to apply this to the other tables, but it's much cleaner now.
Applying the new SQL output system more consistently