Search code examples
sqlstored-proceduresdb2temp-tablesglobal-temp-tables

DB2 Stored Procedures- looping through values?


Okay, so I'm a novice at writing stored procedures. I'm trying to perform a function similar to a foreach() you would see in a programming language. Right now I have a temp table populated with the values I'd like to loop through. I would like to (for each value in this table) execute a SQL statement based upon that value. So, here's my pseudocode to illustrate what I'm really after here:

foreach(value in my temp table) {
  SELECT * FROM TABLE WHERE column_x = value
}

No I know nothing of stored procedures so how can I get this done? Here's my script so far:

DROP TABLE SESSION.X;

CREATE GLOBAL TEMPORARY TABLE
  SESSION.X (
    TD_NAME CHAR(30)
  );

INSERT INTO
  SESSION.X
    SELECT DISTINCT
      TD_NAME
    FROM
      DBA.AFFIN_PROG_REPORT
    WHERE
      TD_NAME IS NOT NULL;

Any help is very much appreciated!


Solution

  • You need, by example, a cursor.

    See the example: https://stackoverflow.com/a/4975012/3428749
    See the documentation: https://msdn.microsoft.com/pt-br/library/ms180169(v=sql.120).aspx