ASPForums.Net RSS Feedhttp://www.aspforums.net/Handlers/RSS.ashxLatest additions to the content that appears on ASPForums.Net(c) 2019 www.aspforums.com. All rights reserved.Generate Columns based on two parameter in SQL Server<p>Hi&nbsp;Richa,</p> <p>Refer below sample query.</p> <p><strong><span style="text-decoration: underline;">SQL</span></strong></p> <pre class="brush: sql">DECLARE @startnum INT SET @startnum = 2018 DECLARE @endnum INT SET @endnum = 2022 ;WITH gen AS ( SELECT @startnum AS YEARS,0 &#39;Amount&#39; UNION ALL SELECT YEARS + 1,0 &#39;Amount&#39; FROM gen WHERE YEARS + 1 &lt;= @endnum ) SELECT * INTO #Temp FROM gen DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) DECLARE @ColumnName AS NVARCHAR(MAX) SELECT @ColumnName = ISNULL(@ColumnName + &#39;,&#39;,&#39;&#39;)+ QUOTENAME(YEARS) FROM (SELECT DISTINCT YEARS FROM #Temp) AS YEARS PRINT @ColumnName SET @DynamicPivotQuery = &#39;;WITH CTE AS(SELECT * FROM #Temp) SELECT DISTINCT &#39;&#39;AMOUNT&#39;&#39; &#39;&#39; &#39;&#39;,&#39; + @ColumnName + &#39; FROM CTE PIVOT (MAX(AMOUNT) FOR AMOUNT IN(&#39;+@ColumnName+&#39;)) p&#39; EXEC(@DynamicPivotQuery) DROP TABLE #Temp</pre> <p><strong><span style="text-decoration: underline;">Output</span></strong></p> <table border="1"> <tbody> <tr> <td>&nbsp;</td> <td>2018</td> <td>2019</td> <td>2020</td> <td>2021</td> <td>2022</td> </tr> <tr> <td>AMOUNT</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> </tr> </tbody> </table>https://www.aspforums.net:443/Threads/980745/Generate-Columns-based-on-two-parameter-in-SQL-Server/https://www.aspforums.net:443/Threads/980745/Generate-Columns-based-on-two-parameter-in-SQL-Server/Mon, 10 Dec 2018 23:28:21 GMT