Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Seems that you are able to get the column names, so I'm assuming you can get to the column types. So you can do this (pesudo code)</p> <pre><code>CREATE TABLE #XXX (Measure &lt;type&gt;) // generate scripts like SET @SQL = N'ALTER TABLE #XXX ADD '+ ColumnName+' '+ColumnTypeInfo EXEC SP_ExecuteSQL @SQL // SET @query = 'INSERT INTO #XXX ([MEASURE], '+@cols+') SELECT [Measure],' + @cols + ' FROM ( SELECT [NewName], [Measure], [Amount] FROM #UnpivottedData x ) x PIVOT ( SUM(Amount) FOR [NewName] in (' + @cols + ') ) p '; EXECUTE(@query); </code></pre> <p>P.S. </p> <ol> <li>I, myself, would choose <code>EXEC sp_executeSQL @SQL</code> over <code>EXEC (@SQL)</code>, but in this case is just a matter of taste</li> <li>I would simplify the code - you don't really need the <code>STUFF</code> part because you need your first comma in your concatenation, so there is no need to remove it. Also, you are forcing an XML column ( with the <code>TYPE</code> clause) only to convert it to <code>NVARCHAR</code></li> </ol> <p><strong>Later edit</strong></p> <p>Disclaimer: this is not tested, as I didn't have your table structure and data</p> <pre><code>DECLARE @cols NVARCHAR(MAX), @query NVARCHAR(MAX), @alter_query NVARCHAR(max); SET @cols = ( SELECT ',' + QUOTENAME(b."NewName") FROM ( SELECT myKey, win = SUM(win) FROM xxx.dbo.yyy GROUP BY myKey ) x INNER JOIN #NameSwitch b ON x.myKey = b.myKey ORDER BY x.win DESC FOR XML PATH('') ) -- this will render smth like ",col1,col2" SET @alter_query = ( SELECT ';ALTER TABLE #XXX ADD ' + QUOTENAME(b."NewName") +' '+ QUOTENAME(b."ColType") +' NULL' FROM ( SELECT myKey, win = SUM(win) FROM xxx.dbo.yyy GROUP BY myKey ) x INNER JOIN #NameSwitch b ON x.myKey = b.myKey ORDER BY x.win DESC FOR XML PATH('') ) -- this will render smth like ";ALTER TABLE #XXX ADD col1 VARCHAR(MAX);ALTER ..." CREATE TABLE #XXX (Measure INT NULL) EXEC sp_ExecuteSQL @alter_query SET @query = 'INSERT INTO #XXX (Measure+'@Cols+') SELECT [Measure]' + @cols + ' FROM ( SELECT [NewName], [Measure], [Amount] FROM #UnpivottedData x ) x PIVOT ( SUM(Amount) FOR [NewName] in (' + STUFF(@cols, 1, 1, '') + ') -- here you need the STUFF to remove the first comma ) p '; EXEC sp_ExecuteSQL @Query SELECT * from #XXX </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload