Dynamic SQL syntax
Only when running 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.
The INTO statement is used 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 this variable corresponds to the sequence of the record values in the query result set.
If parameters need to be dynamically determined, we can use the USING clause.
Dynamic table Creation
Example
- -- Dynamic SQL statement
- Begin
- ExecuteImmediate'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';
- ExecuteImmediate SQL _stmtIntoEmp_rec using emp_id;
- Dbms_output.put_line (emp_rec.phone );
- End;
- ">-- Dynamic insert
- Declare
- SQL _stmtVarchar(200 );
- Emp_id number (10): ='& Emp_id';
- Emp_rec employees % rowtype;
- Begin
- SQL _stmt: ='Insert into employees (id) values (: id )';
- ExecuteImmediate SQL _stmt using emp_id;
- End;
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:
- -- Dynamic SQL and Dynamic Cursor
- Declare
- E_id number (10 );
- E_name varchar2 (50 );
- S_salary number (8 );
- Type c_typeIsRefCursor;
- Cur c_type;
- P_salaty number: ='& P_id';
- Begin
- OpenCurFor
- 'SelectE. id, e.Name, S. salaryvalueFromEmployees e, salary s
- WhereE. id = s. employeeidAndS. salaryvalue>: salOrder ByIdAsc'
- Using p_salry;
- Dbms_output.put_line ('Salary higher'| P_salary |'Employees :');
- Loop
- FetchCurIntoE_id, e_name, s_salary;
- ExitWhenCur % notfound;
- Dbms_output.put_line ('No :'| E_id |'Name :'| E.Name|'Pause'| S_salary );
- EndLoop;
- CloseCur;
- End;