Unable to define cursor based on if else condition

72 Views Asked by At

I am trying to declare cursor based on if else condition in Pro C program and receiving below error when I tried below logic.

I know why it's giving me the below warning but my concern is this approach isn't functioning as expected when I try to open cursor and perform processing based on sqlcode received.

I think we can create two separate cursors then open an one based on the if else condition but just wanted to check if there is any other solution to this?

if(is_valid[0] == 'Y')
{
 EXEC SQL DECLARE cust CURSOR FOR
 select customer, id, price from table1;
}
else
{
 EXEC SQL DECLARE cust CURSOR FOR
 select customer, id, price from table2;
}
}

Error:

PCC-W-02332, attempted to redefine SQL identifier

2

There are 2 best solutions below

0
MT0 On

It looks like the problem is using DECLARE cust twice.

From the Advanced Pro*C/C++ documentation [untested]:

You can try declaring the variable and then passing the declared cursor variable in as a bind variable:

EXEC SQL BEGIN DECLARE SECTION;
    sql_cursor     cust;
EXEC SQL END DECLARE SECTION;

if(is_valid[0] == 'Y')
{
  EXEC SQL EXECUTE
    BEGIN
      OPEN :cust FOR
        select customer, id, price from table1;
    END;
  END-EXEC;
}
else
{
  EXEC SQL EXECUTE
    BEGIN
      OPEN :cust FOR
        select customer, id, price from table2;
    END;
  END-EXEC;
}
0
Gnqz On

I would suggest filtering the data instead of the if statement:

EXEC SQL BEGIN DECLARE SECTION;
    char           var;
EXEC SQL END DECLARE SECTION;

var = is_valid[0];

EXEC SQL DECLARE cust CURSOR FOR
     SELECT customer
          , id
          , price 
       FROM table1
      WHERE 1 = DECODE(:var,'Y', 1, 0)
      UNION ALL
     SELECT customer
          , id
          , price 
       FROM table2
      WHERE 1 = DECODE(:var,'Y', 1, 0);