Query to Make a Horizontal Table Row Vertical
Alek Kirstein
Thursday, April 16, 2009 at 1:35AM —Contributed by William Cassidy, Collectors Universe, Inc. (a unique and awesome developer) – Thanks William!
—Run these queries to generate a series of SQL statements.
—Tweak the source table and WHERE clause if needed.
—Afterward, copy the generated SQL statements into Management Studio and run them. They take about 25 seconds.
—Then, you’ll have a table #temp that contains the values (cast as varchars) of all columns in the table.
SELECT ‘CREATE TABLE #temp (ColumnName varchar(200), Value varchar(7800))’
SELECT ‘INSERT INTO #temp (ColumnName, Value) (SELECT ”’ +
col.[Name] +
”’ AS ColumnName, CAST([’ +
col.[Name] +
‘] AS varchar(7800)) AS Value FROM [some_table] WITH (NOLOCK) WHERE [some_field] = ”40000386”)’
FROM syscolumns col
INNER JOIN sysobjects obj ON obj.id = col.id
INNER JOIN systypes t ON t.xtype = col.xtype
WHERE obj.[Name] = ‘some_table’
Order By col.[Name]
View Printer Friendly Version
Email Article to Friend
Reader Comments