title: SQL Server : cursor Inserting a line if one doesn't exist
body: <p>I've got the following query - a cursor that cycles through a table <code>ltr_program</code> pulling a column (<code>id</code>) inserting that value into a newly created table. It also adds an id field to the newly created table. </p>
  
  <p>I am having a hard time adding logic to say only add that id if it doesn't already exist in the target table (The job will run periodically and new id's will be added as time goes on). I want the code to  be more dynamic only adding newly created data. </p>
  
  <pre><code>DECLARE @next int, @program int
  
  DECLARE insert_cursor CURSOR FOR  
      SELECT id
      FROM ltr_program
  
  OPEN insert_cursor   
  
  FETCH NEXT FROM insert_cursor INTO @program   
  
  WHILE @@FETCH_STATUS = 0 
  BEGIN   
      SET @next = (SELECT MAX(id) FROM LTR_Budget) + 1                     
  
      INSERT INTO LTR_Budget (id, ProgramID) 
          SELECT @next, @program 
  
      FETCH NEXT FROM insert_cursor INTO @program   
  END   
  
  CLOSE insert_cursor
  DEALLOCATE insert_cursor
  </code></pre>
  
  <p>Thank you,</p>