Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin.
Search for scripts directly from SSMS, and instantly access any saved scripts in your
SSC briefcase from the favorites tab.
Download now (direct download link)
Thank this author by sharing:
By John Esraelo,
Some time ago I was being asked if there was a way to denormalize a query result from a 1-to-many related tables/views.
Normally, you would get multiple row results set, in most cases. But, what was being asked was if there was a way to
grab the "many" part and transpose those into a single line with dynamic columns along with the rest of the data from the "1" part of the
At first, I thought that was going to be an easy one and PIVOT popped in my mind rather quickly. Don't get me wrong, it is
still an easy one, but, I was surprised that I was totally misunderstood the question and few minutes later I realized
that I should be on a different path.
PIVOT or the Matrix layouts in Report Builder 3.0 or in MSSQL Analysis Server the "behind the scene" functions
do provide that information to us quickly. So, why are we wasting our time on this? That was my question too!
This script may be helpful if one would like to pass a single parameter, wrap up and transpose the data and drop it on an
online or real-time page or frame for viewing purposes only, then that is great. The key is "real-time" information with the minimum cost.
You may want to alter this code and take it to the next level by make this more dynamic, from accepting TABLE name,
User Name, and even a JOIN statement along with the in question COLUMN and get your result-set dropped on screen.
Hope this may be helpful and useful and enjoy
CREATE THE TEST SROUCE TABLES WITH DATA
DISPLAY THE INSERTED DATA FOR DEBUGGING
CREATE A STAGING TABLE AS A SOURCE TABLE
CREATE ANOTHER STAGING TABLE AS A TARGET FOR THE DENORMALIZED DATA COLUMNS
ALTER TARGET TABLE BY ADDING COLUMNS DYNAMICALLY
LOOP THRU THE DENORMALIZED COUMNS AND UPDATE THE CORRESPONDING COLUMNS
Creating Dynamic Columns in SSRS 2008
Dynamci SQL in creating columns and summary result
How to create dynamic columns in SSRS
Chris Kempster brings us a basic look at the database design topic of denormalization.
Dynamic Column Header with Date