Monday, 12 July 2010

Dynamic Columns in T-SQL


In one of my projects I had to create a SQL query which has dynamic columns. The reason why was related to the fact that I needed to create a pivot table (and that is quiet easy) with dynamic columns. The challange was tricky for me at the time, but when I understood the basics behind it I started to use the method in different ways... and that solved a lot of troubles.
In the web application we are talking about, the user is able to insert and update a table containing the columns, so the pivot table needs to reflect those changes.

By the way, the solution I am explaining is commonly found on the web, so this is not really new to experienced sql programmer.

The trick is to create a stored procedure which first gets the columns, stores them in a variable and then execute the actual pivot query. Let's see it!
DECLARE @columns VARCHAR(8000)
SELECT @columns = COALESCE(@columns + ',[' + cast(tablefield as varchar) + ']', '[' + cast(tablefield as varchar)+ ']')
FROM table
GROUP BY tablefield
In this way we store the columns in a variable (@columns). Now it is easy to use the variable in our actual query like this:
DECLARE @query VARCHAR(8000)
SET @query = 'SELECT ' + @columns +' FROM table
(Aggregate Function(Measure Column)
FOR Pivot Columns IN (' + @columns + ') AS pivTable'

And that's it. If you look closely to the query you will find quite easy to apply it to different situations as I did. Infact I used the same concept to create dynamic where-clause, but that's another story...

1 comment:

  1. This is really a great read for me. Thank you for publishing articles having a great insight stimulates me to check more often for new write ups. Keep posting!



Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.