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 IMMEDIATE
statement to execute a string argument as PL/SQL, which you can make up with ||
as it was intended in the question.
Example:
BEGIN
FOR nr IN 1..102
LOOP
DBMS_OUTPUT.PUT_LINE(nr);
EXECUTE IMMEDIATE
'BEGIN ' ||
'IF rec.column.' || nr ||' is null THEN ' ||
'DBMS_OUTPUT.PUT_LINE(''test''); ' ||
'END IF; ' ||
'END; ';
END LOOP;
END;
Or you could also assign rec.column.' || nr ||' is null
rec.column.' || nr ||' is null
rec.column.' || nr ||' is null
to a variable and make the PUT_LINE
outside the EXECUTE IMMEDIATE
part:
UPDATE : It seems it is not possible to bind BOOLEAN
variables, so I've modified the example to use a NUMBER
.
UPDATE 2: There is a possible efficiency improvement, altough maybe not suitable in this case. Use a constant VARCHAR
for the dynamic SQL, and pass in nr
with 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 null
would execute as 'rec.column.1 is null
, though.
DECLARE
isnull NUMBER;
BEGIN
FOR nr IN 1..102
LOOP
DBMS_OUTPUT.PUT_LINE(nr);
EXECUTE IMMEDIATE
'BEGIN ' ||
'IF rec.column.' || nr ||' IS NULL THEN ' ||
':x:=1; ' ||
'ELSE ' ||
':x:=0; ' ||
'END IF; ' ||
'END; '
USING OUT isnull;
IF isnull = 1 THEN
DBMS_OUTPUT.PUT_LINE('test');
END IF;
END LOOP;
END;
UPDATE 3 : Seeing that:
It is not possible to access rec
inside 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 select
clause to find out if the current column is null:
DECLARE
isnull NUMBER;
rec_id NUMBER; -- Identifier of the fetched record
BEGIN
rec_id := rec.id;
FOR nr IN 1..102
LOOP
DBMS_OUTPUT.PUT_LINE(nr);
EXECUTE IMMEDIATE
'SELECT 1 FROM my_table WHERE id = :idarg ' ||
' AND column_' || nr || ' IS NULL'
INTO isnull USING rec_id;
IF isnull = 1 THEN
DBMS_OUTPUT.PUT_LINE('test');
END IF;
END LOOP;
END;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.