Dynamic SQL syntax
Only at run time can Oracle check whether its format is correct. The INTO and USING clauses are optional. If the SQL statement is a query statement, we can use the INTO clause INTO statement to receive the record value selected by the SELECT statement. It can be a variable sequence or a record-type variable, that is, a record-type variable.
The sequence of the variable sequence corresponds to the sequence of the record values in the query result set. If a parameter needs to be dynamically determined, we can use the USING clause to dynamically create a table.
Example [SQL]
- <Strong> <span style = "font-size: 18px;"> -- dynamic SQL statement
- Begin
- Execute immediate 'create table bonus (id number, ant number )';
- End;
- -- Dynamically query users' phone numbers
- Declare
- SQL _stmt varchar2 (200); -- store query statements
- Emp_id number (10): = '& emp_id ';
- Emp_rec employees % rowtype;
- Begin
- SQL _stmt: = 'select * from employees where id =: id ';
- Execute immediate SQL _stmt into emp_rec using emp_id;
- Dbms_output.put_line (emp_rec.phone );
- End; </span> </strong>
[SQL]
- <Strong> <span style = "font-size: 18px;"> -- Dynamic insert
- Declare
- SQL _stmt varchar (200 );
- Emp_id number (10): = '& emp_id ';
- Emp_rec employees % rowtype;
- Begin
- SQL _stmt: = 'insert into employees (id) values (: id )';
- Execute immediate SQL _stmt using emp_id;
- End; </span> </strong>
The execute immediate statement can only be executed to return one or no results. If you want to write an SQL statement that returns multiple rows, you must use the REF dynamic cursor.
Example: [SQL]
- <Strong> <span style = "font-size: 18px;"> -- dynamic SQL and Dynamic Cursor
- Declare
- E_id number (10 );
- E_name varchar2 (50 );
- S_salary number (8 );
- Type c_type is ref cursor;
- Cur c_type;
- P_salaty number: = '& p_id ';
- Begin
- Open cur
- 'Select e. id, e. name, s. salaryvalue from employees e, salary s
- Where e. id = s. employeeid and s. salaryvalue>: sal order by id asc'
- Using p_salry;
- Dbms_output.put_line ('salary is higher than '| p_salary |' employees :');
- Loop
- Fetch cur into e_id, e_name, s_salary;
- Exit when cur % notfound;
- Dbms_output.put_line ('No.:' | e_id | 'name: '| e. name | 'salary' | s_salary );
- End loop;
- Close cur;
- End; </span> </strong>
-