Oracle – 16 – Dynamic SQL and Dynamic PL/SQL

Dynamic SQL and Dynamic PL/SQL are techniques in Oracle that allow you to construct and execute SQL statements or PL/SQL blocks dynamically at runtime. These techniques provide flexibility in handling situations where you don’t know the SQL statement or PL/SQL block in advance or when you need to generate SQL statements based on runtime conditions. Here’s a brief description of both:

Dynamic SQL:

  1. Dynamic SQL in PL/SQL:
    • Dynamic SQL in PL/SQL allows you to create SQL statements as strings and then execute them using the EXECUTE IMMEDIATE statement or the DBMS_SQL package. This approach is particularly useful when you need to generate SQL statements based on runtime conditions or user inputs.
    DECLARE sql_statement VARCHAR2(100); emp_name VARCHAR2(50); BEGIN sql_statement := 'SELECT employee_name FROM employees WHERE employee_id = :id'; EXECUTE IMMEDIATE sql_statement INTO emp_name USING 101; DBMS_OUTPUT.PUT_LINE('Employee Name: ' || emp_name); END;
  2. Dynamic SQL with Bind Variables:
    • Dynamic SQL often uses bind variables (indicated by :variable_name) to pass values into the SQL statement safely and efficiently. This helps prevent SQL injection and allows for better performance.
  3. Dynamic SQL and DDL:
    • Dynamic SQL is commonly used for executing Data Definition Language (DDL) statements like CREATE, ALTER, or DROP to modify database schema objects dynamically.
    sDECLARE table_name VARCHAR2(30) := 'my_table'; ddl_statement VARCHAR2(200); BEGIN ddl_statement := 'DROP TABLE ' || table_name; EXECUTE IMMEDIATE ddl_statement; EXCEPTION WHEN OTHERS THEN -- Handle exceptions END;

Dynamic PL/SQL:

  1. Dynamic PL/SQL Blocks:
    • Dynamic PL/SQL allows you to construct and execute PL/SQL blocks dynamically. This is often used when you need to generate and execute PL/SQL code based on runtime conditions or user inputs.
    DECLARE plsql_block VARCHAR2(200); BEGIN plsql_block := 'BEGIN ' || ' DBMS_OUTPUT.PUT_LINE(''Hello, Dynamic PL/SQL!''); ' || 'END;'; EXECUTE IMMEDIATE plsql_block; END;
  2. USING Clause:
    • When executing dynamic PL/SQL blocks, you can use the USING clause to pass values into the block, similar to bind variables in dynamic SQL.
    DECLARE emp_id NUMBER := 101; plsql_block VARCHAR2(200); BEGIN plsql_block := 'BEGIN ' || ' INSERT INTO employees (employee_id, employee_name) ' || ' VALUES (:id, ''John Doe''); ' || 'END;'; EXECUTE IMMEDIATE plsql_block USING emp_id; END;

Dynamic SQL and Dynamic PL/SQL are powerful techniques in Oracle that enable you to build flexible, adaptable, and runtime-driven solutions. However, it’s essential to use them with caution, as they can introduce security risks if not handled properly. Always validate and sanitize user inputs and use proper error handling when working with dynamic SQL and PL/SQL.