title: Oracle SQL - How can I write an insert statement that is conditional and looped?
body: <p>Context:
  I have two tables: markettypewagerlimitgroups (mtwlg) and stakedistributionindicators (sdi). When a mtwlg is created, 2 rows are created in the sdi table which are linked to the mtwlg - each row with the same values bar 2, the id and another field (let's call it column X) which must contain a 0 for one row and 1 for the other.
  There was a bug present in our codebase which prevented this happening automatically, so any mtwlg's created during the time that bug was present do not have the related sdi's, causing NPE's in various places. </p>
  
  <p>To fix this, a patch needs to be written to loop through the mtwlg table and for each ID, search the sdi table for the 2 related rows. If the rows are present, do nothing; if there is only 1 row, check if F is a 0 or a 1, and insert a row with the other value; if neither row is present, insert them both. This needs to be done for every mtwlg, and a unique ID needs to be inserted too.</p>
  
  <p>Pseudocode:</p>
  
  <pre><code>For each market type wager limit group ID
      Check if there are 2 rows with that id in the stake distributions table, 1 where column X = 0 and one where column X = 1
      if none
          create 2 rows in the stake distributions table with unique id's; 1 for each X value
      if one
          create the missing row in the stake distributions table with a unique id
      if 2
          do nothing
  </code></pre>
  
  <p>If it helps at all - the patch will be applied using liquibase.</p>
  
  <p>Anyone with any advice or thoughts as to if and how this will be possible to write in SQL/a liquibase patch?</p>
  
  <p>Thanks in advance, let me know of any other information you need.</p>
  
  <p>EDIT:</p>
  
  <p>I've actually just been advised to do this using PL/SQL, do you have any thoughts/suggestions in regards to this?
  Thanks again.</p>