Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Dynamic Pivot Select

Posted on 2014-03-07
4
Medium Priority
?
318 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 41

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 41

Accepted Solution

by:
Sharath earned 1500 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

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

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

     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 …
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

824 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