title: How to write a foreach in SQL Server?
body: <p>I am trying to achieve something along the lines of a for-each, where I would like to take the Ids of a returned select statement and use each of them.</p>
  <pre><code>DECLARE @i int
  DECLARE @PractitionerId int
  DECLARE @numrows int
  DECLARE @Practitioner TABLE (
      idx smallint Primary Key IDENTITY(1,1)
      , PractitionerId int
  )
  
  INSERT @Practitioner
  SELECT distinct PractitionerId FROM Practitioner
  
  SET @i = 1
  SET @numrows = (SELECT COUNT(*) FROM Practitioner)
  IF @numrows &gt; 0
      WHILE (@i &lt;= (SELECT MAX(idx) FROM Practitioner))
      BEGIN
  
          SET @PractitionerId = (SELECT PractitionerId FROM @Practitioner WHERE idx = @i)
  
          --Do something with Id here
          PRINT @PractitionerId
  
          SET @i = @i + 1
      END
  </code></pre>
  <p>At the moment I have something that looks like the above, but am getting the error:</p>
  <blockquote>
  <p>Invalid column name 'idx'.</p>
  </blockquote>