Solved

Dynamically add a new column in a temp table for each row in a query

Posted on 2009-07-09
1
312 Views
Last Modified: 2012-05-07
I need to dynamically add a collection of columns to an existing temp table.  The column names are derived from a separate query and all the columns will have the same data type of varchar (100).  Any ideas?
For example see the psuedo-code below.  

CREATE TABLE #fields

(

	column1 int, 

	column2 varchar(100), 

	colume3 varchar(100)

)
 

FOREACH columnName in SELECT columnName FROM tableName WHERE foo = bar

BEGIN

	EXEC 'ALTER TABLE #fields ADD [' + columnName + '] varchar(100)'

END
 

-- Populate table #temp
 

DROP TABLE #temp

Open in new window

0
Comment
Question by:andy_ee
1 Comment
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 500 total points
ID: 24814813
declare @sql varchar(max)
select @sql = COALESCE(@sql+',', '') +COLUMN_NAME +' VARCHAR (100) '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME  = 'Foo'
EXEC( ' ALTER TABLE #Temp ADD '+@sql )
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

by Mark Wills Attending one of Rob Farley's seminars the other day, I heard the phrase "The Accidental DBA" and fell in love with it. It got me thinking about the plight of the newcomer to SQL Server...  So if you are the accidental DBA, or, simp…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

27 Experts available now in Live!

Get 1:1 Help Now