Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,

I am in a situation where I want to create new table columns from another tables column values.

Table name CITY
Column name Desc

Now, in the CITY table, I have Desc as Mumbai,Pune,Delhi etc.
I want to create a new table CityMast where I want the column names as Mumbai,Pune,Delhi etc.

So how can I create the new table CityMast by taking the values from the CITY table Desc column?

Thnaks in advance..
Posted
Updated 26-Mar-11 0:18am
v2
Comments
Sandeep Mewara 26-Mar-11 6:18am    
No need to bold or use big fonts. It looks rude.

Why would you want to create a new table where you would have row values as column names. This is against the basic rules of relational design guidelines. Yes, you can achieve this by creating a table based on a select statement but what's going to happen when a new city is needed etc.

Tables are not meant to be dynamic what comes to the amount of columns. If this is because of some reporting issue, you should concentrate on creating a good SQL statement, perhaps dynamically and handle the layouting at client side.
 
Share this answer
 
Aothough its not a good practice to change structure regularly...but here is the code

DECLARE @Sql VARCHAR(8000), @Val VARCHAR(50)
SET @Sql = 'CREATE TABLE dbo.CityMast( '

DECLARE cur_Assig CURSOR FOR SELECT DISTINCT Desc FROM City --Assignment names should alo be unique
OPEN cur_Assig
FETCH NEXT FROM cur_Assig INTO @Val

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @Sql = @Sql + @Val + ' VARCHAR(100),' + CHAR(13)

FETCH NEXT FROM cur_Assig INTO @Val
END

SELECT @Sql = LEFT(@Sql,LEN(@SQL) - 1) + ')' --to avoid last comma and add round bracket

--PRINT @Sql
EXEC (@Sql)

CLOSE cur_Assig
DEALLOCATe cur_Assig

To alter the existing table change the logic that select cursor value having those values form city which are not in CtyMast columns (use syscolumns and sysobjects views) and dynamic sql should by alter and executed one by one...or multiple columns should have seperate statements delimeted by the GO statememnt.


Thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900