Example: Creating an SQL Procedure that Specifies Recursion - Advanced SQL Engine - Teradata Database

SQL Data Definition Language Syntax and Examples

Product
Advanced SQL Engine
Teradata Database
Release Number
17.05
Published
January 2021
Language
English (United States)
Last Update
2021-01-22
dita:mapPath
ncd1596241368722.ditamap
dita:ditavalPath
hoy1596145193032.ditaval
dita:id
B035-1144
lifecycle
previous
Product Category
Teradata Vantage™

The following CREATE PROCEDURE definition specifies recursion.

     CREATE PROCEDURE rqspl(
       OUT rowcnt INTEGER)
     BEGIN
         DECLARE target1 INTEGER DEFAULT 0;
         DECLARE target2 INTEGER DEFAULT 0;
         DECLARE target3 INTEGER DEFAULT 0;
         DECLARE finalcount INTEGER DEFAULT 0;
         DECLARE pscursor SCROLL CURSOR FOR
         WITH RECURSIVE RQ(x,y,depth) AS
         (
          SELECT a1, b1, 0
 
          FROM t1
          UNION ALL
          SELECT a1, y, depth+1
 
          FROM RQ,t1
 
          WHERE y = a1
 
          AND   depth < 10
          )
         SELECT *
 
         FROM RQ;
         OPEN pscursor;
         FETCH pscursor INTO target1, target2, target3;
         -- if there is no row from the cursor, 
         -- SQLCODE=7632, SQLSTATE=02000
         WHILE (SQLCODE <> 7632)
         DO
            FETCH pscursor INTO target1, target2, target3;
            SET finalcount = finalcount+1;
         END WHILE;
         CLOSE pscursor;
         SET rowcnt = finalcount;
     END;