Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in

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)

The dynamic unpivoter.

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.

Total article views: 1993 | Views in the last 30 days: 8
Related Articles

Unpivot transformation

multiple columns to unpivot


Remove pivot key column name from UNPIVOT as an outout column

Remove pivot key column name from UNPIVOT as an outout column


how to alter primary key int datatype to uniqueidentifier

how to alter primary key int datatype to uniqueidentifier


Excel Source column DataType

Excel Source column DataType issue


Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones