title: Looping function in PostgreSQL
body: <p>I have a table called nba that has the form</p>
  
  <pre><code>NBA(date DATE, team1 varchar(30), score1 int, team2 varchar(30), score2 int);
  </code></pre>
  
  <p>where team1 is always the winner and team2 is always the loser. Example part of the table:</p>
  
  <pre><code>    date    |         team1          | score1 |         team2          | score2 
  ------------+------------------------+--------+------------------------+--------
   2013-10-29 | Indiana Pacers         |     97 | Orlando Magic          |     87
   2013-10-29 | Miami Heat             |    107 | Chicago Bulls          |     95
   2013-10-29 | Los Angeles Lakers     |    116 | Los Angeles Clippers   |    103
   2013-10-30 | Cleveland Cavaliers    |     98 | Brooklyn Nets          |     94
   2013-10-30 | Philadelphia 76ers     |    114 | Miami Heat             |    110
  </code></pre>
  
  <p>I'm trying to write a function that takes in a team, loops through the game list, and transfers the "title" to any team that beats that winning team. For example, the beginning team could be 'Miami Heat'. The next team that beats the heat will be the champion, taking the title away from the heat. The next team to beat that team will pass the title on them, etc. So if the Magic beat the Heat and the Lakers then beat the Magic, the lakers would currently hold the title. I want to iterate through the table and complete this 'passing' of the title all the way through the end and return the last team to have the title at the end of the list. </p>
  
  <p>My current attempt looks like this: </p>
  
  <pre><code>--Declare function and specify argument as a team that holds title at beginning
  
  CREATE FUNCTION findChamp(thechamp varchar(30)) RETURNS void as 
  
  $func$
  -- Set current champ to argument passed in 
  DECLARE
          r nba%rowtype;
          champ varchar(30) = thechamp;
  BEGIN
          FOR r in Select * from nba
          LOOP
          IF team2 = champ -- If the champ lost
                  champ = team1; -- Champ is now the team it lost to
          END IF;
          END LOOP;
          RETURN champ; -- Return the final champ
  END;
  $func$
  LANGUAGE 'plpgsql';
  </code></pre>
  
  <p>I'm new to writing functions in postgres and don't think this is too sound. I'm currently getting an error of </p>
  
  <pre><code>psql:function.psql:16: ERROR:  missing "THEN" at end of SQL expression
  LINE 10:   champ = team1;
  </code></pre>
  
  <p>. Where am I going wrong? I've added THEN statements in multiple places and none seem to fix the problem, I believe I'm off significantly on syntax somewhere. Any pointers are appreciated</p>