title: Using a cursor with dynamic SQL in a stored procedure
body: <p>I have a dynamic SQL statement I've created in a stored procedure. I need to iterate over the results using a cursor. I'm having a hard time figuring out the right syntax. Here's what I'm doing.</p>
  
  <pre><code>SELECT @SQLStatement = 'SELECT userId FROM users'
  
  DECLARE @UserId
  
  DECLARE users_cursor CURSOR FOR
  EXECUTE @SQLStatment --Fails here. Doesn't like this
  
  OPEN users_cursor
  FETCH NEXT FROM users_cursor
  INTO @UserId
  
  WHILE @@FETCH_STATUS = 0
  BEGIN
  
  EXEC asp_DoSomethingStoredProc @UserId
  
  END
  CLOSE users_cursor
  DEALLOCATE users_cursor
  </code></pre>
  
  <p>What's the right way to do this?</p>