2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
SQL is an extremely powerful and hard to master language. It may be tempting to emulate SQL joins in PL/SQL using nested cursor loops, but those are not optimized by Oracle at all. In fact, they lead to numerous context switches between the SQL and PL/SQL engines, and those switches have a highly negative impact on performance. It is therefore much better to replace nested PL/SQL cursor loops with native SQL joins.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-04-28 16:49:39 +02:00
----
SET SERVEROUTPUT ON
CREATE TABLE countriesTable(
countryName VARCHAR2(42)
);
CREATE TABLE citiesTable(
cityName VARCHAR2(42)
);
INSERT INTO countriesTable VALUES('India');
INSERT INTO countriesTable VALUES('Switzerland');
INSERT INTO countriesTable VALUES('United States');
INSERT INTO citiesTable VALUES('Berne');
INSERT INTO citiesTable VALUES('Delhi');
INSERT INTO citiesTable VALUES('Bangalore');
INSERT INTO citiesTable VALUES('New York');
BEGIN
FOR countryRecord IN (SELECT countryName FROM countriesTable) LOOP
FOR cityRecord IN (SELECT cityName FROM citiesTable) LOOP -- Non-Compliant
DBMS_OUTPUT.PUT_LINE('Country: ' || countryRecord.countryName || ', City: ' || cityRecord.cityName);
END LOOP;
END LOOP;
END;
/
DROP TABLE citiesTable;
DROP TABLE countriesTable;
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-04-28 16:49:39 +02:00
----
SET SERVEROUTPUT ON
CREATE TABLE countriesTable(
countryName VARCHAR2(42)
);
CREATE TABLE citiesTable(
cityName VARCHAR2(42)
);
INSERT INTO countriesTable VALUES('India');
INSERT INTO countriesTable VALUES('Switzerland');
INSERT INTO countriesTable VALUES('United States');
INSERT INTO citiesTable VALUES('Berne');
INSERT INTO citiesTable VALUES('Delhi');
INSERT INTO citiesTable VALUES('Bangalore');
INSERT INTO citiesTable VALUES('New York');
BEGIN
FOR myRecord IN (SELECT * FROM countriesTable CROSS JOIN citiesTable) LOOP -- Compliant
DBMS_OUTPUT.PUT_LINE('Country: ' || myRecord.countryName || ', City: ' || myRecord.cityName);
END LOOP;
END;
/
DROP TABLE citiesTable;
DROP TABLE countriesTable;
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Use a native join here rather than a nested PL/SQL cursor loop
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]