This is a stored procedure to transpose N rows from a specified table.
Version 2.0 allows the user to specify the schema in @TableName (the schema defaults to [dbo]).
I have found copying a transposed table to Excel useful for reviewing data from a table with many columns. A transposed table derived from a limited number of rows will not exceed Excel's maximum number of columns, and the transposed data is often easier to navigate and read.
Other transpose procedures I have found on the web are somewhat limited: they assume the columns in the original table are of the same numeric data type. This procedure handles tables with columns of varying data types; the workaround is to cast all data in the output table as varchar(max).
Also, please note that this procedure does NOT return a crosstab table. Crosstabs return summary data (totals or counts), not the original data. In certain specific circumstances (when the cases in a base table are unique) a crosstab procedure can return a transpose of the original data. Again, however, this use is limited to numeric data.
A portion of the procedure was adapted from MSDN community content. Thanks to the original posting member (Brindha Raji) and additional revising members. Please see the procedure code for the reference URL.
EXEC usp_TransposeNRows @TableName [, @NRows]
||Name of table to be transposed (REQUIRED)
||Format: [<SchemaName>.]<TableName> (<SchemaName> defaults to [dbo])
||Number of rows to transpose (OPTIONAL; Default = 0, max = 1022)
||When @NRows = 0, just the column order and column names of the table are returned.