To reinforce what Terisa de morgan said:
1) A template computes a value that is used in the template's context, such as in a composite column. A template by itself cannot set the value of a column. It might be possible to force a custom template function to write something into the database but that would break all sorts of rules and would likely have unpleasant side effects.
2) You set the value of a column using a calibre function. The choices are (approximately):
- Edit metadata/single
- Edit metadata/bulk
- Search & Replace
- Manual editing on the spreadsheet
- A plugin that does the operation you want
- Calibre's command line functions
- A standalone python program that uses calibre's database API.
Of course, it is possible to write a program that directly manipulates metadata.db without using calibre functions. I strongly suggest that you don't go there because the likelihood of getting something wrong is very high.
My feeling is that a plugin or standalone program would be easier to write and maintain than the complex S&R expressions and templates that you are currently building. But as you say, doing so requires knowledge you don't currently have. Evaluating the trade off is up to you.