Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
Dear Frnds,

I need to change rows as columns I have used this code.. this code is executed but all values comes null.. but more than 20 values are in database.
What is the mistake in this code.. please ASAP

SQL
DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ItemName +'_'+c.col) 
                      from Vw_DailyEntry
                      cross apply 
                      (
                        select 'MatQty' col
                        union all
                        select 'Rate'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(ItemName +'_'+c.col) 
               +' as ['
               + ItemName + case when c.col = 'MatQty' then ']' else ' Rate]' end
             from Vw_DailyEntry
             cross apply 
             (
                select 'MatQty' col
                union all
                select 'Rate'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'select RetDate,DPNo,
 ' + @colsName + ' 
from
(
  select DPNo,RetDate,
    ItemName +''_''+col col,  
    MatQty 
  from
  (
    select DPNo,ItemName,RetDate,
    cast(MatQty as numeric(10, 2)) mtqty,
    cast(Rate as numeric(10, 2)) rates    
    from  Vw_DailyEntry
  ) src
  unpivot
  (
    MatQty 
    for col in (mtqty,rates)
  ) unpiv
) s
pivot
(
  Max(MatQty)
  for col in (' + @cols + ')
) piv'

execute(@query)
Posted
Updated 7-Oct-15 4:35am
v5
Comments
Member 12003400 7-Oct-15 4:53am    
This will be difficult to understand.Please put your data structure and desired output.
Sinisa Hajnal 7-Oct-15 4:56am    
1. what is QUOTENAME?
2. Does your select FOR XML returns correct rows when you execute it (in query analyzer, not calling this from the code)
Maciej Los 7-Oct-15 6:17am    
QuoteName is SQL Server inbuild function which returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.
Sinisa Hajnal 7-Oct-15 6:48am    
Everyday, there is something new :) Thanks.
Maciej Los 7-Oct-15 6:59am    
You're very welcome.

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