0
DECLARE @query VARCHAR(max)
DECLARE @years VARCHAR(max)

SELECT  @years = STUFF(( SELECT DISTINCT '],[' + ltrim(str(Years)) FROM 
                 #Inquires ORDER BY '],[' + ltrim(str(Years)) desc FOR XML 
                 PATH('')), 1, 2, '') + ']'    

SET @query = 'INSERT INTO Table_Name SELECT * 
              FROM (SELECT ReportDate, Company, EventType, Years,Months#,
                    Months,Inquires FROM #Inquires
                    WHERE Company = ''Company_Name'')t PIVOT (SUM(Inquires) 
                    FOR Years IN ('+@years+')) AS pvt ORDER BY Company, Months#'

EXECUTE (@query)

I am getting this error while executing this code:

Column name or number of supplied values does not match table definition

This code is running fine in SQL Server 2008, but not in SQL Server 2014.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jay Mehta
  • 19
  • 6
  • Print your SQL before executing. Perhaps it me, but the @years looks odd to me – John Cappelletti Mar 29 '17 at 20:43
  • For SQL server 2016/2017/.. see here [error message sql server 2016/2017/...](https://stackoverflow.com/questions/1152932/column-name-or-number-of-supplied-values-does-not-match-table-definition/52592071#52592071) – FredyWenger Oct 01 '18 at 13:19

1 Answers1

1

I'm guessing that you now have more years returned from your pivot than you have in your table.

Try specifying your column names for your insert and in your select.

SqlZim
  • 37,248
  • 6
  • 41
  • 59