title: Is there a better way to execute dynamic SQL that doesn't use a cursor?
body: <p>I have dynamic SQL stored in a SQL table that I have to execute under certain conditions. Currently, we use cursors to handle that for us, but I was always told to avoid cursors when possible as they aren't the most efficient way of doing things. So, my question is: how do I execute dynamic SQL without them (if there's a way)? The entire system is built around this dynamic SQL mess, so there is no changing it. </p>
  
  <p>For this, just assume the table has <code>Id AS IDENTITY</code> and <code>SQL AS VARCHAR</code> fields, where the SQL field contains the SQL to be executed (obviously). </p>
  
  <p><strong>EDIT:</strong> 
  Basically, I want to loop through the table and execute the SQL in the SQL column.</p>
  
  <p>So, a row in the table will basically look like this:</p>
  
  <pre><code>ID   SQL
  --   ----------------------
  1    SELECT * FROM RECORD
  2    SELECT * FROM PERSON
  3    SELECT * FROM LOCATION
  </code></pre>
  
  <p>I haven't written any code because what I'd write is a cursor to traverse through the table and execute it. I just don't know of any other ways of looping a table and executing that string as a SQL query other than something like:</p>
  
  <pre><code>DECLARE @sql VARCHAR(MAX)
  
  DECLARE _cursor CURSOR
  FOR
      SELECT  [SQL]
      FROM    #tmp2
  
  OPEN _cursor
  
  FETCH NEXT FROM _cursor INTO @sql
  
  WHILE @@FETCH_STATUS = 0 
      BEGIN
          PRINT ( @sql )
      END
  CLOSE _cursor   
  DEALLOCATE _cursor
  </code></pre>