Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys,

i want to assign table column name from other table column data.

Scenario:

I have one table, Departments, in which i have 5 depts
n
other table units, each dept has its own units.

Now, i want these unit names as table column names.

i mean, i'll create one temp table whose column names could be the units names.

In stored procedure or any other way.

Can i do this, is it possible.

In SQL-SERVER-2008-R2


can anyone please help me.

Thanks
Posted
Comments
Praveen Kumar Upadhyay 8-Dec-14 1:09am    
Means you want to convert Rows value into columns? your data is something like
Unit1
Unit2
Unit3
and you want something like
Unit1 Unit2 Unit3
abdul subhan mohammed 8-Dec-14 1:25am    
yes, please

Have a look at the PIVOT operator in SQL Server:
http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx[^]
 
Share this answer
 
Check out below Articles.

http://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-columns-in-sql-server[^]

In the above article, it is clearly defined that how you can convert your Rows into columns, if your Rows(Unit in your case) is fix or not fix.

Please accept the solution, if it is solving your problem.

Thanks
 
Share this answer
 
hi,

try it with below,it might be sol your problem.
*****************Main *********************start
SQL
DECLARE @SEL NVARCHAR(MAX)
SET @SEL='select
        0 unit_id from Unit_table
         group by unit_name
    '



     exec dynamic_pivot @SEL

     ,'unit_name'

     ,'AVG(unit_id )'
       print @SEL
     select * into #temp1  from ##tmp213

select * from #temp1 

     DROP TABLE ##tmp213

DROP TABLE #temp1

*****************Main *********************End

First Execute this

CREATE procedure dynamic_pivot

(

@select varchar(2000),

@PivotCol varchar(100),

@Summaries varchar(100)



-- GET DATA IN PIVOT COLUMN

) as

declare @pivot varchar(max), @sql varchar(max)

select @select =replace(@select,'select ','select '+@PivotCol+' as
pivot_col,')





create table #pivot_columns (pivot_column varchar(100))



Select @sql='select distinct pivot_col from ('+@select+') as t'



insert into #pivot_columns

exec(@sql)



select @pivot=coalesce(@pivot+',','')+'['+pivot_column+']'from
#pivot_columns



select @sql=

'

select * INTO ##tmp213 from

(

'+@select+'

) as t

pivot

(

'+@Summaries+' for pivot_col in ('+@pivot+')

) as p

'



exec(@sql)





DROP TABLE #pivot_columns
 
Share this answer
 
Check my article hope this will help you.

Basic SQL Queries for Beginners[^]
 
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