// During the stored procedure, we often copy the field data queried from a table to a write variable,
// Call the function dbms_output.put_line () in the package to print it out;
// The following is an instance:
Procedure show_employee (empno_in emp. empno % type)
As
V_sign number;
V_empno emp. empno % type;
V_ename emp. ename % type;
V_deptno emp. deptno % type;
Begin
Select 1 into v_sign
From dual
Where exists (select count (*) from emp where empno = empno_in );
If v_sign = 1 then
Select empno, ename, deptno into v_empno, v_ename, v_deptno
From emp where empno = empno_in;
Dbms_output.put_line ('information of '| empno_in | 'are :');
Dbms_output.put_line ('empno: '| v_empno |', ename: '| v_ename |', deptno: '| v_deptno );
End if;
Exception
When others then
Dbms_output.put_line ('no data found ');
End show_employee;
SQL> exec show_employee ('20140901 ');
Information of7900 are:
Empno: 7900, ename: JAMES, deptno: 30
//
// But how can we reverse the structure of a table using a stored procedure?
// It is the write process. The parameter is the name of the input table, and all fields of the input table are printed;
Create or replace procedure pro_display_col (table_name_in varchar2)
As
Type arry_type is table of varchar2 (30) index by pls_integer;
V_cols arry_type;
Begin
Select tc. column_name bulk collect
Into v_cols
From user_tab_columns tc
Where tc. table_name = upper (table_name_in );
For I in 1 .. v_cols.count
Loop
Dbms_output.put_line (v_cols (I ));
End loop;
Exception
When others then
Dbms_output.put_line (sqlerrm );
End pro_display_col;
/
// Resolution:
// A nested table data type is defined here, which is generally called an array with no maximum limit,
// It defines a string type that receives the returned value, 30 bytes, 15 characters
// We can also define it as a nested table that accepts 30 characters:
// Type array_type is a table of varchar2 (30 char) index by pls_integer;
// Index by pls_integer is used to obtain column_name data. v_cols.extend is not required.
// Open up space for the retrieved data display. If there is no index by pls_integer,
// Every time we get the data, we need to open up the space for its display, v_cols.extend;
// About bulk collect
// You can use bulk collect to load the query results to collections at a time.
// Instead of processing it one by one Using cursor.
SQL> exec pro_display_col ('emp ');
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
//
SQL> exec pro_display_col ('dept ');
DEPTNO
DNAME
LOC
//
// The simplest way to obtain table fields is as follows:
SQL> col data_type format a13;
SQL> select column_name, data_type, data_length, data_precision, data_scale
2 from user_tab_columns
3 where table_name = upper ('emp ');
COLUMN_NAME DATA_TYPE DATA_LENGTH DATA_PRECISION DATA_SCALE
------------------------------------------------------------------------------
Empno number 22 4 0
ENAME VARCHAR2 10
JOB VARCHAR2 9
Mgr number 22 4 0
Hiredate date 7
Sal number 22 7 2
Comm number 22 7 2
Deptno number 22 2 0
//