Can a database query be written inside a template.php file?
You can definitely do it, however you really shouldn't.

The theme layer is for presenting the data.
The actual functionality and the data itself should come from modules.

If you mention what you are trying to do I can give some more information on where it should go instead

Edit

Based on your code example, if you are dealing with a custom data table the best thing would be to use hook_views_data() to let views know about your database table and fields. Then you would just use your new fields via the UI.

If you didn't want to go to that much trouble though you could use basically the same solution as you are using now in a custom module in one of the views hooks, like hook_views_post_execute(), where you can loop through the results in a similar fashion as you are doing now.

You generally wouldn't be dealing with markup here though (like your abc_code div). You're really only changing data here and then changing markup in the theme. Although your field should already have classes that let you specifically style it so adding that class probably shouldn't be necessary.