I am new in PL/SQL. I have a problem with loop in this language. I’ d like to make loop like this:
FOR nr IN 1..102
LOOP
DBMS_OUTPUT.PUT_LINE(nr);
IF rec.column_||nr IS NULL
THEN
DBMS_OUTPUT.PUT_LINE('test');
END IF;
END LOOP;
I have created a cursor. As you can see I’ d like to check all column with names column from column_1 to column_102. Unfortunately || operator does not work for this situation.
Do you know some solution to my problem?
You can do this with dynamic PL/SQL. Use an
EXECUTE IMMEDIATEstatement to execute a string argument as PL/SQL, which you can make up with||as it was intended in the question.Example:
Or you could also assign
rec.column.' || nr ||' is nullto a variable and make thePUT_LINEoutside theEXECUTE IMMEDIATEpart:UPDATE: It seems it is not possible to bind
BOOLEANvariables, so I’ve modified the example to use aNUMBER.UPDATE 2: There is a possible efficiency improvement, altough maybe not suitable in this case. Use a constant
VARCHARfor the dynamic SQL, and pass innrwith a binded variable. This is even more efficient than using native SQL if in a large loop. I don’t think'rec.column.:arg is nullwould execute as'rec.column.1 is null, though.UPDATE 3:
Seeing that:
It is not possible to access
recinside the dynamic SQL statement because it is undefined (out of scope),It seems not possible to pass a non-sql type as an argument to the dynamic statement (record, cursor)
A possible workaround is to bind some id columns (SQL Type) to the dynamic statement, and use a
selectclause to find out if the current column is null: