Search SupportSQL
« get row counts for all tables in a database | Main | “Homegrown Compliance” Series – default trace Data Acquisition and sample view »
Thursday
16Apr2009

Query to Make a Horizontal Table Row Vertical

—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]

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.
Member Account Required
You must have a member account on this website in order to post comments. Log in to your account to enable posting.