Ok I have been pondering the idea of dynamic columns, what I mean by this is a table of columns named January......December.
User at runtime would select a month range such as Feb to July.
What I would normally do is fetch all columns from my code behind then sort the ones I need and ones I don't.
But I was wondering a way to do this all in SQL.
I know SQL doesn't support arrays (sad face) but there are alternatives.
So my question is, is there a way for a SQL query to be set-up that dynamically selects a number of columns depending on a parameter that is a range of column names?
I've looked at some dynamic query's, but they only do 1 column.
I'm thinking along the lines of passing a string of columns provided by the code behind as 1 param in the SQL, then somehow iterate through to select each column.
What do you guys think? cant be Done? can be done but messy?
EDIT: thought I would provide some code, as you can see I apply a pivot query and get a range of columns (months). What's being suggested so far is to normalise first then pivot.
SELECT
[1] January ,
[2] February,
[3] March,
[4] April,
[5] May,
[6] June,
[7] July,
[8] August,
[9] September,
[10] October,
[11] November,
[12] December
FROM
(
SELECT MONTH(Convert(datetime,[lasttaken],120)) as months, complete
FROM #Temp WITH(NOLOCK)
) d
pivot
(
count(complete)
for months in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) p