title: Dynamic PIVOT SQL Server - form/inputs example
body: <p>I need to transform the SELECT (<a href="https://i.stack.imgur.com/rtOWb.png" rel="nofollow noreferrer">image here</a>) in a dynamic PIVOT, where there can be any forms name and each form can have different inputs name and amounts.</p>
  
  <p>I already did the script to set columns according to the max number of inputs in a form. But I am not sure how to procced after that.</p>
  
  <pre><code>DECLARE @ColumnName AS NVARCHAR(MAX);
  DECLARE @i INT = 1;
  
  DECLARE @max int = 
      (SELECT
    MAX(y.qtd)
  FROM (SELECT TOP 10
    frm_Form,
    frm_Name,
    COUNT(inp_Input) AS qtd
  FROM orb_Forms
  INNER JOIN orb_FormInputs
    ON frm_Form = fri_Form
  INNER JOIN orb_Inputs
    ON fri_Input = inp_Input
  WHERE frm_Operation = 1
  AND frm_Enabled = 1
  AND fri_Enabled = 1
  AND inp_Enabled = 1
  GROUP BY frm_Form,frm_name
  ORDER BY frm_Form desc) y)
  
  WHILE (@i &lt;= @max)
      BEGIN
          select @ColumnName = ISNULL(@ColumnName + ',','') + QUOTENAME('Input' + CAST(@i as nvarchar));
          SET @i = @i + 1;
      END
  </code></pre>
  
  <p>Result: [Input 1],[Input 2],[Input 3],[Input 4],[Input 5],[Input 6],[Input 7],[Input 8],[Input 9],[Input 10],[Input 11]</p>