Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 ADD DYNAMIC COLUMNS FROM VALUES WITHIN A TABLE

Author  Topic 

misterdeey
Starting Member

19 Posts

Posted - 2011-07-05 : 14:36:38
Hi,
I have table A that looks like :

----------------------------------
FIRST_NAME | LAST_NAME | STATE |
----------------------------------
JOHN | ABCD | AL |
MARK | EFGH | NY |
GEORGE | IJKL | CO |

And table B as:

------------------------
FIRST_NAME | LAST_NAME |
------------------------
JOHN | ABCD |
MARK | EFGH |
GEORGE | IJKL |

What I need to do is to dynamically add columns name to table B to where the SQL statement will add columns name based off of the state column values from table A so Table B will look as:

--------------------------------------------
FIRST_NAME | LAST_NAME | AL | NY | CO |
--------------------------------------------
JOHN | ABCD | 0 | 0 | 0 |
MARK | EFGH | 0 | 0 | 0 |
GEORGE | IJKL | 0 | 0 | 0 |

Thanks much for your help.
YAZ

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-07-05 : 14:44:17
You need to use dynamic sql for this. See

http://sqlblogcasts.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2011-07-06 : 08:45:54
No, what you need to do is design this correctly and not add columns to tables dynamically. 1st Normal Form is your FRIEND.


http://weblogs.sqlteam.com/jeffs/archive/2008/05/13/question-needed-not-answer.aspx
How to ask: http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

For ultra basic questions, follow these links.
http://www.sql-tutorial.net/
http://www.firstsql.com/tutor.htm
http://www.w3schools.com/sql/default.asp
Go to Top of Page

misterdeey
Starting Member

19 Posts

Posted - 2011-07-06 : 16:47:55
visakh16: Thanks much it worked as a charm :)
Go to Top of Page

misterdeey
Starting Member

19 Posts

Posted - 2011-07-15 : 12:06:06
Thanks
Go to Top of Page
   

- Advertisement -