I have created a cursor, that returns some data. I then wish to have an if statement in the returned data that checks if the field 'test_field' exists in the cursor where test_field2='A'. I am struggling to get my syntax correct on the if statement though, and can't find any pointers online.
CURSOR test_cur IS
SELECT *
FROM test
where name=pk_name;
BEGIN
FOR trec IN test_cur LOOP
--The following line where my syntax is incorrect
IF trec.test_field EXISTS IN test_cur WHERE trec.test_field2 = 'A' THEN
{logic code to go here}
END IF;
...
Example data:
name | test_field | test_field2
--------------------------------------
x | 101 | ROL
x | 101 | A
x | 102 | ROL
x | 103 | ROL
On the first loop of the cursor we have the following:
trec.name=x
trec.field=101
trec.field2=ROL
What I want it to do though, is realise that there is another row (y) where where test_field=101 and test_field2='A' and therefor go into the if statement.
I'd rather suggest checking this condition within the query you use for he cursor, smth like this:
That syntax does not look logical to me, AFAIK you cannot do that
a solution would be
I'm guessing here that when you say 'trec.test_fields exists where test_field = trec.test_field' you mean that you have a separate variable named
test_field
in your program somewhere. If that's the case, change the name of the variable tostrTest_field
to prevent naming collisions between the variable and the field in the table, and change your cursor to something like:Share and enjoy.
You can't peek ahead to later cursor records, and running the cursor multiple times would be expensive and possibly not helpful anyway.
You could order the data in the cursor such that your
'A'
record always comes first, and then use tracking variables to see whether you have had an'A'
record for the currentname
/test_field
combination:A neater approach might be to add a flag to every record in the cursor, using analytic functions to to the 'peeking' ahead in the result set; again this assumes your
'A'
value actually comes first alphabetically, if it doesn't then the function would need to be tweaked to get your actual value first:... or even better, since this doesn't rely on the alphabetic order of your target value and also gives you a clearer result:
Putting that in the cursor gives:
Note that this also doesn't force you to process the
'A'
record first in the loop, which may or may not be important - probably not as you weren't ordering at all in the example.If i understand your query correctly you are looking to peek ahead only. If so you must know the field that defines your order. I have given the template to do that below.
The specific statement of interest to solve your syntax question is:
FOR trec IN test_cur LOOP --The following line where my syntax is incorrect
and below restated the full template:
...