I have an excel sheet which is bound to a stored procedure. In the stored procedure I am selecting the columns that appear in the excel sheet. Now I'm facing an issue when I wanted to add some more columns:
- Some value 2016
- Some value 2017
- Some value 2018
The first column is adding the actual year to the header and the two others the next one and the year after the next one.
My problem is that I don't know how to do this dynamically. I've tried something like this:
DECLARE @actualYear INT = YEAR(GETDATE())
SELECT tab.Name,
myTable.SomeValue [Some value @actualYear],
myTableNext.SomeValue [Some value @actualYear+1],
myTableAfterTheNext.SomeValue [Some value @actualYear+2]
FROM SomeTable tab
LEFT JOIN MyTable myTable ON tab.SomeId = myTable.SomeId
AND myTable.[Year] = @actualYear
LEFT JOIN MyTable myTableNext ON tab.SomeId = myTableNext.SomeId
AND myTable.[Year] = (@actualYear+1)
LEFT JOIN MyTable myTableAfterTheNext ON tab.SomeId = myTableAfterTheNext.SomeId
AND myTable.[Year] = (@actualYear+2)
The output is the following:
+------+------------------------+--------------------------+--------------------------+
| Name | Some value @actualYear | Some value @actualYear+1 | Some value @actualYear+2 |
+------+------------------------+--------------------------+--------------------------+
Second try:
SELECT tab.Name,
myTable.SomeValue ['Some value' + @actualYear]
...
Output:
+------+----------------------------+ ...
| Name | 'Some value' + @actualYear | ...
+------+----------------------------+ ...
How can I get the correct column headers dynamically?