title: CURSOR with Update Column Name Variable
body: <p>This is my first post on any forum asking for help with SQL. I have always found the answer I need by searching (usually on this site).</p>
  
  <p>I have a cursor with a variable column name and a where clause that includes the column name.</p>
  
  <p>Can anybody tell me why it says many rows were updated but my data never changes? #WHold is a temp table that holds the column names I need to loop through. It also relates to the row data value. I could use a pivot table but I am curious why this cursor is not working.</p>
  
  <p>If I run an update statement the rows are updated.</p>
  
  <p>---My Update statement---</p>
  
  <pre><code>UPDATE MT
  SET MT.[10004] = MTD.WHoldAmt
  FROM dbo.MyData MT 
          INNER JOIN dbo.MyDataDetail MTD
          ON MT.EEID = MTD.EEID AND MTD.WHold = '10004'
  </code></pre>
  
  <p>---My CURSOR---</p>
  
  <pre><code>DECLARE @ColumnName VARCHAR(100)
  DECLARE @getColumnName CURSOR
  DECLARE @MTColumnName VARCHAR(100)
  
  SET @getColumnName = CURSOR FOR
  SELECT WHold,'MT.['+WHold+']' FROM #Whold
  
  OPEN @getColumnName
  FETCH NEXT FROM @getColumnName INTO @ColumnName,@MTColumnName
  WHILE @@FETCH_STATUS = 0
  
  BEGIN
      UPDATE MT
      SET @MTColumnName = MTD.WHoldAmt
      FROM dbo.MyData MT 
      INNER JOIN dbo.MyDataDetail MTD ON MT.EEID = MTD.EEID AND MTD.WHold = @ColumnName
  FETCH NEXT
  FROM @getColumnName INTO @ColumnName,@MTColumnName
  
  END
  CLOSE @getColumnName
  DEALLOCATE @getColumnName
  </code></pre>
  
  <p>---Results from cursor though none of the data was changed in the table MyData---</p>
  
  <p>(531 row(s) affected)</p>
  
  <p>(8 row(s) affected)</p>
  
  <p>(2757 row(s) affected)</p>
  
  <p>(1 row(s) affected)</p>
  
  <p>(2 row(s) affected)</p>
  
  <p>(1 row(s) affected)</p>
  
  <p>(14 row(s) affected)</p>
  
  <p>(461 row(s) affected)</p>
  
  <p>(511 row(s) affected)</p>
  
  <p>(17 row(s) affected)</p>
  
  <p>(9 row(s) affected)</p>
  
  <p>(3 row(s) affected)</p>
  
  <p>Thank you</p>