Solved

Dynamic Pivot Select

Posted on 2014-03-07
4
301 Views
Last Modified: 2014-03-11
I have been struggling with this.

I use a dynamic select list of fields that I then use to get data on.
e.g. SELECT FieldName FROM MandatoryTable
Result in comma delimited list = 'Date of Incorporation','Country of Incorporation' etc etc.

I then SELECT the data against a "Client" table for the these fields leading with a primary key.
Record set = 'Client1','2013-02-01','England'
Client2,Null,'France'
etc
etc

What I actually want is the result set to be sent to a table or temp table and to be pivoted;
Columns would be: ClientID / FieldName / FieldValue
Record Set; 'Client1', 'Date of Incorporation', '2013-02-01'
'Client2','Date of Incorporation','Null'
etc
etc

I am currently stuck with this code;

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

-- GET LIST OF DYNAMIC FIELDS TO PASS TO FINAL SELECT
select @cols = STUFF(
                  (
                        SELECT
                              distinct ',' + QUOTENAME(REPLACE(TFN.[FieldName],'''','_'))
                    FROM
                                    [ChangeLogFields] AS CLS
                              JOIN
                                    [TableFieldNames] AS TFN
                                    ON TFN.[TableNo] = CLS.[Table No_]
                                    AND TFN.[FieldNo] = CLS.[Field No_]
                              WHERE
                                    TFN.[TableName] = 'Client'
                                    AND CLS.[Mandatory] <> 0
                              
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

-- SET QUERY TO EXECUTE AND PIVOT
set @query = '
            (
                  SELECT
            [Client No_],
                  ' + @cols + '
            FROM
                        Client
         )
           PIVOT
           (
                  [FieldName]
                  FOR [Client No_]  
                  IN ' + @cols + '
           ) AS PivotTable
            '
           
execute(@query);

Thanks in advance.
0
Comment
Question by:BrightRaven
  • 2
  • 2
4 Comments
 
LVL 40

Expert Comment

by:Sharath
ID: 39913633
I think you need an Unpivot here. Try this if this gives what you are looking for Date and Country columns.
 If this is your expected output, you can replace the columns list with a variable and execute the query dynamically.
 SELECT [Client No_],FieldName,FieldValue
   FROM Client
UNPIVOT (FieldValue FOR FieldName IN ([Date of Incorporation],[Country of Incorporation])) P

Open in new window

0
 

Author Comment

by:BrightRaven
ID: 39917071
Thanks for response Sharath.

FieldName and FieldValue do not exist in the table Client? Not sure how this works!
0
 
LVL 40

Accepted Solution

by:
Sharath earned 500 total points
ID: 39919013
check this
 SELECT [Client No_],FieldName,FieldValue
   FROM (select [Client No_],
                convert(varchar(20),[Date of Incorporation]) 'Date of Incorporation',
				[Country of Incorporation]
           from Client) T1
UNPIVOT (FieldValue FOR FieldName IN ([Date of Incorporation],[Country of Incorporation])) P

Open in new window

http://sqlfiddle.com/#!3/959bf/5
0
 

Author Closing Comment

by:BrightRaven
ID: 39920737
Although not the full final solution. It steered me to it. Thank you.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

     When we have to pass multiple rows of data to SQL Server, the developers either have to send one row at a time or come up with other workarounds to meet requirements like using XML to pass data, which is complex and tedious to use. There is a …
Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now