Dynamic PIVOT in T-SQL or somewhere else?

In a
recent thread on dynamic SQL, the issue of dynamic PIVOT came up.
Dynamic PIVOT can be implemented in T-SQL with dynamic SQL:
Pivots with Dynamic Columns in SQL Server 2005
http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/
http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query
http://www.sqlusa.com/bestpractices2005/dynamicpivot/
Alternatives:
1. Enhancement by MS to the current static PIVOT which has limited use since it is not data-driven
2. Use SSRS which has built-in dynamic columns
3. Use client app
What is your opinion? Is it OK to use dynamic SQL for dynamic PIVOT?
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

solution elsewhere, for instance with Tablix in SSRS. Pivoting a result set in C# should not be too difficult
But I could do it much faster in T-SQL with dynamic SQL. 
If your shop has a reporting system like SSRS and the request is for permanent report, then by all means, SSRS is the choice with built-in dynamic columns.
C#? I used to know C/C++. So that is not a choice for me. On the other hand, if you are competent in C#, then it may be a better choice, or it may not.
I'm not sure why people tend to shy away from dynamic SQL, for me, I've never had any problems or issues. Is there any specific reason for this?
Maybe the multiple single quotes like '''' in concatenation of the dynamic SQL string? When one looks at the following example, it is easy to see that dynamic SQL adds a new level of complexity to static SQL. Yet, the complexity pays off with incredible
dynamic SQL programming power.
BLOG: Building Dynamic SQL In a Stored Procedure
Code example from the blog:
/* This stored procedure builds dynamic SQL and executes
using sp_executesql */
Create Procedure sp_EmployeeSelect
/* Input Parameters */
@EmployeeName NVarchar(100),
@Department NVarchar(50),
@Designation NVarchar(50),
@StartDate DateTime,
@EndDate DateTime,
@Salary Decimal(10,2)
AS
Set NoCount ON
/* Variable Declaration */
Declare @SQLQuery AS NVarchar(4000)
Declare @ParamDefinition AS NVarchar(2000)
/* Build the Transact-SQL String with the input parameters */
Set @SQLQuery = 'Select * From tblEmployees where (1=1) '
/* check for the condition and build the WHERE clause accordingly */
If @EmployeeName Is Not Null
Set @SQLQuery = @SQLQuery + ' And (EmployeeName = @EmployeeName)'
If @Department Is Not Null
Set @SQLQuery = @SQLQuery + ' And (Department = @Department)'
If @Designation Is Not Null
Set @SQLQuery = @SQLQuery + ' And (Designation = @Designation)'
If @Salary Is Not Null
Set @SQLQuery = @SQLQuery + ' And (Salary >= @Salary)'
If (@StartDate Is Not Null) AND (@EndDate Is Not Null)
Set @SQLQuery = @SQLQuery + ' And (JoiningDate
BETWEEN @StartDate AND @EndDate)'
/* Specify Parameter Format for all input parameters included
in the stmt */
Set @ParamDefinition = ' @EmployeeName NVarchar(100),
@Department NVarchar(50),
@Designation NVarchar(50),
@StartDate DateTime,
@EndDate DateTime,
@Salary Decimal(10,2)'
/* Execute the Transact-SQL String with all parameter value's
Using sp_executesql Command */
Execute sp_Executesql @SQLQuery,
@ParamDefinition,
@EmployeeName,
@Department,
@Designation,
@StartDate,
@EndDate,
@Salary
If @@ERROR <> 0 GoTo ErrorHandler
Set NoCount OFF
Return(0)
ErrorHandler:
Return(@@ERROR)
GO
LINK:
http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Similar Messages

  • How to Handle Dynamic Pivoting with a single SQL?

    I was searching for a single SQL who can dynamically understands the pivoting members in the data, I saw several ways of doing Pivoting depending on the version, some are really hard to understand but just two options upto now seams to be flexable enough to do dynamic pivoting, right?
    1- For this option you have to write PL/SQL block to build up the dynamic single SQL query, I also find this approach very easy to understand. :)
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:766825833740
    2- 11.1 's PIVOT new feature with PIVOT XML and ANY clause, a SINGLE SQL and easy to understand but returns XMLTYPE data, another step to parse to produce the report is needed.
    http://www.oracle-developer.net/display.php?id=506
    Below is a 10g Model Clause example, but here instead of pivoting by A1-A2-A3 staticly I want to have these values by a distinc subquery for example;
    create table test(id varchar2(2), des varchar2(4), t number);
    INSERT INTO test values('A','a1',12);
    INSERT INTO test values('A','a2',3);
    INSERT INTO test values('A','a3',1);
    INSERT INTO test values('B','a1',10);
    INSERT INTO test values('B','a2',23);
    INSERT INTO test values('C','a3',45);
    commit;
    SELECT * FROM test;
    ID DES T
    A a1 12
    A a2 3
    A a3 1
    B a1 10
    B a2 23
    C a3 45
    select distinct i, A1, A2, A3
    from test c
    model
    ignore nav
    dimension by(c.id i,c.des d)
    measures(c.t t, 0 A1, 0 A2, 0 A3)
    rules(
    A1[any,any] = t[cv(i),d = 'a1'],
    A2[any,any] = t[cv(i),d = 'a2'],
    A3[any,any] = t[cv(i),d = 'a3']
    I A1 A2 A3
    C 0 0 45
    B 10 23 0
    A 12 3 1 Any advice is appreciated, thank you.

    Hi,
    You can do dynamic SQL in SQL*Plus, also.
    [Thid thread|http://forums.oracle.com/forums/thread.jspa?messageID=2744039&#2744039] shows how to pivot a table with a dynamic number of columns.

  • Setting Column Names in Dynamic Pivot Query

    Hi all,
    I'm having trouble setting column names in a dynamic pivot query and was wondering if someone could please help me figure out what I need to do.
    To help you help me, I've setup an example scenario in my hosted account. Here's the login info for my hosted site at [http://apex.oracle.com]
    Workspace: MYHOSTACCT
    Username : DEVUSER1
    Password : MYDEVACCTAnd, here is my test application info:
    ID     : 42804
    Name   : dynamic query test
    Page   : 1
    Table 1: PROJECT_LIST         (Alias = PL...  Listing of Projects)
    Table 2: FISCAL_YEAR          (Alias = FY...  Lookup table for Fiscal Years)
    Table 3: PROJECT_FY           (Alias = PF...  Intersection table containing project fiscal years)
    Table 4: PROJECT_FY_HEADCOUNT (Alias = PFH... Intersection table containing headcount per project and fiscal year)Please forgive the excessive normalization for this example, as I wanted to keep the table structure similar to my real application, which has much more going on.
    In my sample, I have the "Select Criteria" region, where the user specifies the project and fiscal year range that he or she would like to report. Click the Search button, and the report returns the project headcount in a pivoted fashion for the fiscal year range specified.
    I've got it working using a hard-coded query, which is displayed in the "Hardcoded Query" region. In this query, I basically return all years, and set conditions on each column which determines whether that column should be displayed or not based on the range selected by the user. While this works, it is not ideal, as there could be many more fiscal years to account for, and this is not very dynamic at all. Anytime a fiscal year is added to the FISCAL_YEAR table, I'd have to update this page.
    So, after reading all of the OTN SQL pivot forums and "Ask Tom" pivot thread, I've been able to create a second region labeled "Dynamic Query" in which I've created a dynamic query to return the same results. This is a much more savvy solution and works great; however, the column names are generic in the report.
    I had to set the query to parse at runtime since the column selection list is dynamic, which violates SQL rules. Can anyone please help me figure out how I can specify my column names in the dynamic query region to get the same column values I'm getting in the hardcoded region?
    Please let me know if you need anymore information, and many thanks in advance!
    Mark

    Hi Tony,
    Thanks so much for your response. I've had to study up on the dbms_sql package to understand your function... first time I've used it. I've fed my dynamic query to your function and see that it returns a colon delimited list of the column names; however, I think I need a little more schooling on how and where exactly to apply the function to actually set the column names in APEX.
    From my test app, here is the code for my dynamic query. I've got it in a "PL/SQL function body returning sql query" region:
    DECLARE 
      v_query      VARCHAR2(4000);
      v_as         VARCHAR2(4);
      v_range_from NUMBER;
      v_range_to   NUMBER;         
    BEGIN
      v_range_from := :P1_FY_FROM;
      v_range_to   := :P1_FY_TO;
      v_query      := 'SELECT ';
      -- build the dynamic column selections by looping through the fiscal year range.
      -- v_as is meant to specify the column name as (FY10, FY11, etc.), but it's not working.
      FOR i IN v_range_from.. v_range_to  LOOP
        v_as    := 'FY' || SUBSTR(i, 3, 4);
        v_query := v_query || 'MAX(DECODE(FY_NB,' || i || ',PFH_HEADCOUNT,0)) '
          || v_as || ',';
      END LOOP;
      -- add the rest of the query to the dynamic column selection
      v_query := rtrim(v_query,',') || ' FROM ('
        || 'SELECT FY_NB, PFH_HEADCOUNT FROM ('
        || 'SELECT FY_ID, FY_NB FROM FISCAL_YEAR) A '
        || 'LEFT OUTER JOIN ('
        || 'SELECT FY_ID, PFH_HEADCOUNT '
        || 'FROM PROJECT_FY_HEADCOUNT '
        || 'JOIN PROJECT_FY USING (PF_ID) '
        || 'WHERE PL_ID = ' || :P1_PROJECT || ') B '
        || 'ON A.FY_ID = B.FY_ID)';
      RETURN v_query;
    END;I need to invoke GET_QUERY_COLS(v_query) somewhere to get the column names, but I'm not sure where I need to call it and how to actually set the column names after getting the returned colon-delimited list.
    Can you (or anyone else) please help me get a little further? Once again, feel free to login to my host account to see it first hand.
    Thanks again!
    Mark

  • Dynamic Pivot with Select Into

    I have this Dynamic Pivot which works fine.
    DECLARE @query VARCHAR(4000)
    DECLARE @years VARCHAR(2000)
    SELECT @years = STUFF(( SELECT DISTINCT'],[' + [factor_label]
    FROM [TEMP_lacp_factors]
    ORDER BY '],[' + [factor_label]
    FOR XML PATH('')
    ), 1, 2, '') + ']'
    SET @query =
    'SELECT * FROM
    SELECT [date_],[issue_id],[cusip],[Factor_value],[factor_label]
    FROM [TEMP_lacp_factors]
    )t
    PIVOT (MAX([factor_value]) FOR [factor_label]
    IN ('+@years+')) AS pvt'
    EXECUTE (@query)
    I'm trying to take the results of that and do a SELECT INTO, so I can move the results to another table.  Is this possible?  I didn't find a whole lot online.
    The error that I'm getting is this.
    Caused by: Column name or number of supplied values does not match table definition.
    How can I do this?  Is it even possible?
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Sure, you can create a table with SELECT INTO, but it cannot be a #temptable. Well, it can be a #temptable, but it will disappear as soon as you exit the scope it was created it, that is the dynamic SQL.
    The question is only, what would you do with this table later? Since you don't know the column names, about all work will have to be done through dynamic SQL.
    A dynamic pivot is a non-relational operation. A SELECT statement produces a table, and a table describes a distinct entity, of which the column are distinct and well-defined attributes. Something which your dynamic pivot does not adhere to.
    There is only one thing you can do with your dynamic pivot: returning the data to the client. I don't know what you want to do with that table, but probably you should do that manipulation before the dynamic pivot, because as I said: that is always your
    last step.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • DYNAMIC PIVOT - Problem with variables

    Dear All,
    I'm working on a Query that makes use of Dynamic Pivot
    It is intented to give a summarized list of Income and Expenses month by month
    I have adapted the foll. Query from SAP B1 Forum to my problem:
    Re: Date Wise Production Report
    Unfortunately my adaptation does not work.
    When I run it, the following Selection Criteria screen appears. I input the dates as below:
    Query - Selection Criteria
    Posting Date        Greater or Equal            01.01.11
    Posting Date        Smaller or Equal            31.12.11
    [OK]      [Cancel]
    On pressing [OK], I receive this error message:
    Incorrect Syntax near 20110101
    Grateful if anybody could help me spot my mistake (It's likely to be within Section 2)
    Thanks
    Leon Lai
    Here's my adapted SQL
    /*Section 1*/
    DECLARE @listCol VARCHAR(2000)
    DECLARE @query VARCHAR(4000)
    /*Section 2*/
    SELECT @listCol =
    STUFF(
    ( SELECT DISTINCT
    '],[' + CONVERT(VARCHAR, MONTH(T0.RefDate), 102)
    FROM JDT1
    FOR XML PATH('')
    , 1, 2, '') + ']'
    /*Section 3*/
    SET @query =
    SELECT * FROM
    SELECT
    T0.Account,
    T1.GroupMask,
    T1.AcctName,
    MONTH(T0.RefDate) as [Month],     
    (T0.Debit - T0.Credit) as [Amount]
    FROM dbo.JDT1 T0
    JOIN dbo.OACT T1 ON T0.Account = T1.AcctCode
    WHERE
    T1.GroupMask IN (4,5,6,7) AND
    T0.[Refdate] >= '[%1]'AND
    T0.[Refdate] <= '[%2]'
    ) S
    PIVOT
    Sum(Amount)
    FOR [Month] IN ('+@listCol+')
    ) AS pvt
    /*Section 4*/
    EXECUTE (@query)

    Hi,
    try to update where condition as  :
    T0.[Refdate] >= ' + cast ([%1] as nvarchar) + ' AND
    T0.[Refdate] <= ' + Cast([%2] as Nvarchar) + '
    Thanks,
    Neetu

  • IR with dynamic pivot

    Hi all
    We have been designing resource management system and want to provide flexible way to extend resource properties at runtime. So we are storing resource properties in a single table, e.g.
    select * from _kv
    ID K V
      1  name Bob
      1  age  30
      1  gender male
      2  name Susan
      2  status married
    convert to
    +-----+-------+--------+----------+
    | key | color | height | whatever |
    +-----+-------+--------+----------+
    | 1   | green | 15     | ---      |
    | 2   | ---   | ---    | lol      |
    +-----+-------+--------+----------+
    example of dynamic pivot Dynamic SQL Pivoting &amp;#8211; Stealing Anton&amp;#8217;s Thunder&lt;/title&gt; //&lt;title&gt;AMIS Technology Blog…
    Is it possible to create interactive report with dynamic columns updated when _kv will be changed?
    Is it possible to create add/edit dynamic form depends on key set if we add value type description?
    Thanks

    make sure you put some thought into your database design before you go too far.
    There are many horror stories about EAV based schema designs. (which this design seems to be heading.)
    Read up on them before you go too far.
    -- back to being on topic --
    AFAIK you can not do dynamic SELECT with an Interactive Report.
    However, you can with a Basic Report.  But, it is non-trivial. (ie it is difficult to do)
    Basic Report can use a "function returning SELECT statement".
    You will also need to name the columns based on a different function.
    In order to 'synchronize' the column names with the SELECT statement, you will need a 3rd function that properly generates them.
    This 3rd function MUST have an 'ORDER BY' clause.
    Both the generateSELECT() function and the generateCOLUMN_NAMES() function will call that 3rd function.
    From a code management standpoint, you will need to create a package that contains all three functions.
    are you sure you want to go this route?
    are you ready to go this route?
    Again, think about your table designs.
    MK

  • Whenever I try to save a file as a PDF, it tells me it can't save because the file is open somewhere else. This is not the case and I have tried it with different files. Please help. You can also call me at:(301)651-9616

    Whenever I try to save a file as a PDF, it tells me that it can't save, because the file is open somewhere else. I don't have anything else open. I have also tried different files and they all say the same thing. Help.

    Given there are so many problems and removed features in Pages 5, why not just continue using Pages '09?
    http://www.freeforum101.com/iworktipsntrick/viewforum.php?f=22&mforum=iworktipsn trick
    http://www.freeforum101.com/iworktipsntrick/viewtopic.php?t=432&mforum=iworktips ntrick
    Peter

  • Dynamic table pulled from SQL database, Need to Search

    My table results are not static, they are pulled into a
    dynamic table from a SQL database. Each table displays 10 records
    with an option at the bottom to display additional records
    (next/previous), for my query. I also have an option set up to
    allow users to click for a detail view of a record in the table. If
    the table data was static, I would be able to set up a search
    option and a results page for it, but I'm dealing with dynamic data
    on an .ASP page. I'd like to set up a search box to limit the
    records displayed in the table. I haven't found any code samples
    that are designed for dynamic data.
    Here is a copy of the code from my table.

    Hi,
    I think the code on this URL will get you the solution
    http://www.asp.happycodings.com/Array/code3.html
    Cheers,
    ~Maneet

  • I have a 32 gb ipad air but need to get the songs stored in iTunes on my old iMac onto the ipad air or stored somewhere else. I have over 10000 songs on there which is 30.47 gb so far too much to put on my ipad air. How do I get them off my old iMac which

    I have a 32 gb ipad air but need to get the songs I have stored in iTunes on my old iMac onto the ipad air or stored somewhere else. I have over 10000 songs on there which is 30.47 gb. far too much to put on my ipad air. How do I get them off my old iMac which has no internet connection ? And where do I put them. Any help would be appreciated

    No I don't have another computer. I was thinking initially I would put them on my ipad but since I don't have enough gb maybe I can store them in some cloud thing? Sorry am a bit of a Luddite when it comes to all this. I just need to have them stored someplace and accessible to play when I need to. Thanks for your help.

  • Email Enabled lists - where to run the SMTP server? On APP server or on Exchange Server? Or somewhere else?

    Hi there,
    I need to setup EMail Enabled lists in SharePoint 2010 site. Where do I need to run the SMTP server? On APP server or on Exchange Server? Or somewhere else?
    Thank you so much.

    The SMTP service cannot run on the Exchange server. You can run it on a SharePoint server, or a stand alone server and share out the drop directory over SMB.
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • Firefox 4 will not let me keep my bookmarks listed on the side bar. I can open them there but once I click somewhere else they go away.

    Firefox 4 will not let me keep my bookmarks listed on the side bar. I can open them there but once I click somewhere else they go away. On previous Firefox versions I could display my bookmark folders down the left side of my screen and just leave them there, accessing saved bookmarks when I needed to. Now with FF4 I can open a vertical column of my bookmark folders by clicking on bookmarks in the navigation bar but this won't stay there; if I click elsewhere they disappear. I could put a bookmark toolbar on my screen but this takes up more vertical space. I have lots of horizontal space that's unused. How can I go back to the display of bookmarks in previous versions?

    You can fix that by going to View -> Sidebar and click on Bookmarks.
    Or you could simply use a shortcut
    ''control + B''

  • How can i get itunes to quit skipping to the currently playing song when i'm working on the library somewhere else?

    how can i get itunes to quit skipping to the currently playing song when i'm working on the library somewhere else?

    You might be able to achieve what you want by using Party Shuffle. Set the source for Party Shuffle to be the playlist you want to listen to or add the tracks you want to listen to by control clicking on them and selecting Add to Party Shuffle. Once everything is in Party Shuffle, you can rearrange them to your satisfaction. As the songs are played, they'll roll off the queue. You can quit iTunes and even when you restart, all your songs will be there, in the order you want, waiting for you to hit play.

  • I need to send encoded Blu Ray File to be Burned somewhere else?

    Usually I click burn Blu ray in Final Cut’s share feature and I run it all the way through to create disc.
    Now I would like to send the encoded file to get burnt somewhere else.
    What would be the best recommended way to do this and keep the menu intact and what would they need to burn the Blu Ray disk, they have Final Cut Studio as well.
    Thank you.

    Deyson wrote:
    On their end, will they need to just drag and drop to do a burn?
    I would imagine so, but I've never done so I'm not sure. You have a blu-ray burner right? Try it out. make an image and then try to burn it.
    According to http://www.kenstone.net/fcphomepage/burn_br_mac_superdrivestone.html
    +If you select 'Hard Drive (Blu-ray)' and create a Disk Image, you will only be able to burn this Disk Image to a Blu-ray disc using a Blu-ray burner.+ This tutorial is how to burn a AVCHD disc with a DVD burner.

  • HT4623 I'm trying to update my ipod iOS...when it says to go into "Settings/General/Software Update", I don't have a "Software Update" option in my General category.  Is there somewhere else I need to look in order to get iOS updates?

    I'm trying to update my ipod iOS...when it says to go into "Settings/General/Software Update", I don't have a "Software Update" option in my General category.  Is there somewhere else I need to look in order to get iOS updates?

    Updating from the ipod itself is a feature of ios 5 or later.
    You would need to update as always.  Turn on computer, open itunes, connect ipod.
    The first gen ipod will only go to 3.1.3

  • I recently upgraded our iMac to Yosemite OS and now have a problem with Photoshop Elements 11:  the move tool selects an image or text layer, but then I try to drag the selection somewhere else on the page and it snaps back to the original location, howev

    I recently upgraded our iMac to Yosemite OS and now have a problem with Photoshop Elements 11:  the move tool selects an image or text layer, but then I try to drag the selection somewhere else on the page and it snaps back to the original location, however the arrows will move it OK.  Also I cannot drag the selection to another photo in the photo bin as before.

    Hi,
    Please refer: http://helpx.adobe.com/photoshop-elements/kb/pse-stops-responding-yosemite.html
    Thanks,
    Anwesha

Maybe you are looking for