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 Corcoran,
If you're ever stuck in a situation where you want to unpivot a table even a temp table this SP will solve your problems.
The sp takes 3 arguements. The first being the name of the table that you want to unpivot, an optioinal second paramenter for the tableSchema. By default the SP will use the dbo schema. Finally, the third parameter is an output paramater to capture any errors.
example: exec [usp_dynamic_unpivot] '#test','dbo',''
There is only one prerequisite. The table you want to unpivot must have primary key(s). If not the SP will have no idea what to pivot on. It needs the primary key to normalize the table. The output is a table with the primary key(s) as columns and two additional columns called columnName and value. The columnName column will contain all the pivoted column names and the value column will contain all the columnName values.
Since a null value can't be unpivoted all nulls are translated to a blank string. Also, since the source of the data in the value column could be any datatype all datatypes are translated to a varchar(255) string. Simply, update the SP if you need a longer string value. Obvioulsy, you will not be able to unpivot a text, image, xml datatype datatype.
So, if you're ever stuck with having to compare a wide pivoted out table between two databases, simply run the unpivoter on each table, store the results in two temp tables. Then you can simply join the two tables on the primary key and list out all the diffs.
multiple columns to unpivot
Remove pivot key column name from UNPIVOT as an outout column
how to alter primary key int datatype to uniqueidentifier
Excel Source column DataType issue