Click here to Skip to main content
15,893,790 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have one table #table with columns columnname,value

having contents say...
SQL
Columnname      value

XYZ              NUll
ABC              null


another table I have say #datatable with Columns XYZ, ABC, LMN and having data

SQL
XYZ      ABC         LMN

 1       2           3




I need to update first #table the result of the sql query as,

SQL
ColumnName      Value
XYZ             1
ABC             2



Please help

here is what I tried

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
					 
select @cols = STUFF((SELECT ',' + QUOTENAME(columnname) 
                    from #table
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
print @cols
set @query = N'SELECT ' + @cols + N' from 
             #datatable
               unpivot 
            (
            value    
        for columnname in (' + @cols + N')
            ) p '

but error

Msg 207, Level 16, State 1, Line 1
Invalid column name 'XYZ'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'ABC'.
Posted
Updated 30-Oct-14 1:48am
v3
Comments
King Fisher 30-Oct-14 7:33am    
How did u get the Value of XYZ,ABC ..
Member 10112611 30-Oct-14 7:34am    
you mean in second table? this is just a test entry I made to express my requirement
King Fisher 30-Oct-14 7:55am    
actually What do u want to Do? Explain From the Beginning of your Task .its not Clear

You can Un-Pivot the #datatable table and then make a simple updated as you will have
below values and format after unpivot

XYZ 1
ABC 2
LMN 3
 
Share this answer
 
Comments
Member 10112611 30-Oct-14 7:13am    
I tried one query , but error, can u help me on Solving
this?
King Fisher 30-Oct-14 7:27am    
What have you tried so far?
Member 10112611 30-Oct-14 7:48am    
I modified and added the query I tried and the error message also
Member 10112611 30-Oct-14 7:27am    
Columns or rows of both table are not predefined is one of the constraint..there can be n number of rows for the first table and n numebr of columns for second one
Member 10112611 30-Oct-14 7:58am    
Hi shweta ,

I tried the above query to unpivot, but error. can u help?
SQL
SELECT  COLUMNANME,VALUE  from
             #datatable
               unpivot
            (
            value
        for COLUMNANME in (XYZ,ABC)
            ) p
 
Share this answer
 
Thank you for the helps from all to reach at unpivot concept
 
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