T4 Templates are a code generation tool that come packaged in Visual Studio. What that means exactly is that if you have a repeatable pattern, you can use this tool to iterate over that pattern and fill in the blanks where there are differences.
Use Case Example
On the project in which I learned how to use this tool, we generated merge procs for an ETL. The T4 Template iterated over a database schema which supplied us with the tables and column names. The template provided all the parts that were the same. Originally, I had crafted something with dynamic SQL, which was convenient and what I knew how to use. I quickly learned that the beauty of the T4 Template is that it leverages the .Net framework, which handles text and formatting much more elegantly than SQL.
Generating Partitions in SSAS
So I recently had the need to create a cube which would have 2 years of daily partitions. If you have ever used the partition editor in Visual Studio, you’d quickly realize that this was intended to only create a handful of partitions. Doing this work manually would be nuts.
I looked in the SSAS project folder and found a file called <Project Name>.partitions, which contained a specification for all of the partitions that I had created so far. It was roughly like this:
<Cube …bunch of namespaces…>
….Other attributes about the partition including the query which defines it…
So in order to create more partitions, we only need to add more partition nodes, changing the Id, name, query which defines it and some guids. I added a new c# project to my solution and added a new T4 Template file called partitions.tt. This looked like below:
When a tt file is saved, it’s code is executing and the resulting file is created below it with the specified extension. The syntax of this file is a little funky and there is no highlighting out of the box. For highlighting and intellisense, I used the visual studio extension Devart T4 Editor which is free.
Some key aspects to note are:
- Declarations are noted within <#@ #>
- i.e. you can reference a data assembly and make a connection out to a database
- The default language is c#, but this can be changed to VB if you prefer
- “output extension” specifies the file type
- All gray text below is left unchanged in the final file
- All text within <# #> is c# code
- For example, I start by declaring a couple of variables and the reference them in a while loop
- At the start of each loop I set variables like the query text
- At the end of each loop the date is incremented
- To insert the value of a variable, you merely need to break the text with <# variableName #>
Below is a full code example: