Dynamic SQL statements are a powerful way to execute dynamic queries in PL/SQL. In this approach, queries are designed as the program proceeds or when the conditions arise. There are two tools in PL/SQL to design and execute dynamic queries.
1) Native Dynamic SQL (NDS)
2) DBMS_SQL package
NDS is relatively easy to use when compared to DBMS_SQL package. DBMS_SQL has a complex structure for making dynamic queries.
Using NDS, inputs can be passed to a query statement and outputs can be collected.
While writing dynamic queries, we can follow two approaches. Parts and inputs of a dynamic query can be attached to each other dynamically using string concatenation and then the dynamic query can be executed, or , placeholders can be used to pass parameters/inputs to a dynamic query. Using placeholder technique is a safer approach as it prevents SQL injection attacks.
Now let's see how to use NDS
CREATE OR REPLACE PROCEDURE proc(p_id IN number, p_name OUT varchar2)
IS
user_id number(6);
query_text varchar2(500);
BEGIN
user_id := p_id;
query_text := 'UPDATE employee_data SET salary=1.1*salary WHERE id = :1 RETURNING name INTO :2';
EXECUTE IMMEDIATE query_text USING user_id RETURNING INTO p_name;
COMMIT;
END;
Create/replace the above procedure and call it. This dynamic query executes the update statement by taking id as input and returns the name of the employee who has got the hike.
Let's see one more example with select statement.
CREATE OR REPLACE PROCEDURE proc(p_id IN number, p_name OUT varchar2)
IS
user_id number(6);
query_text varchar2(500);
BEGIN
user_id := p_id;
query_text := 'SELECT name FROM employee_data WHERE id = :1';
EXECUTE IMMEDIATE query_text INTO p_name USING user_id;
END;
This select statement saves the name of the employee in p_name variable for a given id.
For more info visit
No comments:
Post a Comment