Illustration of dynamic SQL query generation and execution with examples and best practices

6.What is the difference between EXECUTE IMMEDIATE and DBMS_SQL?
•EXECUTE IMMEDIATE: Used for simple, single-statement Dynamic SQL.
•DBMS_SQL: Supports more complex use cases, such as dynamically binding arrays or handling multiple statements.
Example with DBMS_SQL:
DECLARE
v_cursor INTEGER;
v_query VARCHAR2(200);
BEGIN
v_query := 'SELECT COUNT(*) FROM employees WHERE department_id = :dept_id';
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, v_query, DBMS_SQL.NATIVE);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':dept_id', 101);
DBMS_SQL.CLOSE_CURSOR(v_cursor);
END;


7.How can you execute DDL statements using Dynamic SQL in Oracle?
DDL statements, such as CREATE, DROP and ALTER, must be executed using EXECUTE IMMEDIATE.
Example:
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE employees ADD (bonus NUMBER)';
END;
Dynamic SQL is necessary to run DDL because static SQL does not support such operations.


8.How would you handle multiple dynamic conditions in Oracle's Dynamic SQL?
Dynamic SQL can form queries with multiple conditions dynamically, based on runtime inputs.
Use conditional statements to build the query string.
Declaration:
DECLARE
v_query VARCHAR2(200) := 'SELECT * FROM employees WHERE 1=1';
v_dept_id NUMBER := 101;
v_min_salary NUMBER := 50000;
BEGIN
IF v_dept_id IS NOT NULL THEN
v_query := v_query || ' AND department_id = ' || v_dept_id;
END IF;
IF v_min_salary IS NOT NULL THEN
v_query := v_query || ' AND salary >= ' || v_min_salary;
END IF;
EXECUTE IMMEDIATE v_query;
END;


9.How do you debug Dynamic SQL in Oracle?
To debug Dynamic SQL, use DBMS_OUTPUT.PUT_LINE to print the constructed query before executing it. This would help in syntax errors or logic issues.
Example Debugging:
DECLARE
v_query VARCHAR2(200);
BEGIN
v_query := 'SELECT * FROM employees WHERE department_id = 101';
DBMS_OUTPUT.PUT_LINE(v_query); -- Outputs the query for debugging
EXECUTE IMMEDIATE v_query;


10.What are some practical applications of Dynamic SQL in Oracle?
Dynamic SQL is applied to the following types of situations:
•Dynamic report generation.
•Automating DDL operations, such as table creation.
•Dynamic table or column names.
Example: Dynamic column selection:
DECLARE
v_query VARCHAR2(200);
v_column VARCHAR2(50) := 'salary';
BEGIN
v_query := 'SELECT ' || v_column || ' FROM employees';
EXECUTE IMMEDIATE v_query;.