title: Dynamic SQL error when using pivot command
body: <pre><code>IF OBJECT_ID('tempdb..#temp1') IS NOT NULL DROP TABLE #temp1
  GO
  
  CREATE TABLE #TEMP1 
  (
    COUNTER nvarchar(200),SEQUENCE INT   
  )
  INSERT INTO #TEMP1 VALUES ('Counter1','1')
  INSERT INTO #TEMP1 VALUES ('Counter2','2')
  INSERT INTO #TEMP1 VALUES ('Counter3','3')
  INSERT INTO #TEMP1 VALUES ('Counter4','4')
  INSERT INTO #TEMP1 VALUES ('Counter5','5')
  INSERT INTO #TEMP1 VALUES ('Counter6','6')
  INSERT INTO #TEMP1 VALUES ('Counter7','7')
  INSERT INTO #TEMP1 VALUES ('Counter8','8')
  INSERT INTO #TEMP1 VALUES ('Counter9','9')
  INSERT INTO #TEMP1 VALUES ('Counter10','10')
  
  --select * from #TEMP1
  
  
  DECLARE @query AS NVARCHAR(MAX)=''
  DECLARE @Counter nvarchar(1000)
  DECLARE @Cols As NVARCHAR(MAX)=''
  
  declare  MyCursor cursor
  for SELECT  DISTINCT A.SEQ
      FROM tblSEQUENCE A 
      open MyCursor
  fetch next from MyCursor into @Counter
  while @@FETCH_STATUS=0
  BEGIN
  
      Set @Cols = @Cols + 'Counter'+@Counter+''   
      fetch next from MyCursor into @Counter
  END
  CLOSE MyCursor;  
  DEALLOCATE MyCursor
  set @Cols= stuff(@Cols,len(@Cols),1,'')
  print @Cols
  
  set @query = 'SELECT ' + @cols + ' FROM (select B.METER_VALUE As VALUE,A.SEQ AS SEQUENCE,T.COUNTER AS COUNTER
                      from tblCOUNTER B,tblSEQUENCE A INNER JOIN #TEMP1 T
                       ON A.SEQ=T.SEQUENCE)
                               x
              pivot 
              (
                  max(VALUE)
                  for COUNTER in (' + @cols + ')
              ) p '
  
  --print @query
  execute(@query)
  </code></pre>
  
  <p>i need to pivot maximum value to corresponding counter based on sequence.</p>
  
  <p>My result needs to be look like </p>
  
  <pre><code>Counter_1   Counter_2   Counter_3   Counter_4   Counter_5
  29823       29823       29823       29823       29823
  </code></pre>
  
  <p>How can i achieve this? i am frequently getting error is too long. Maximum length is 128</p>