Stored procedures are commonly used in programs, and I often write some in projects. But I make a mistake: I always write the SQL statement process into a long string of SQL statements, run the SQL statement normally. As a result, the code is too long, and the database needs to be modified.
For example, the primary keys of two tables table1, table2, and table1 are used as the Foreign keys of table 2. To insert data
- StringSQL ="
- Declare
- Cid number;
- Begin
- Select count (a. id) into cid from table1 a where 1 = 1;
- IfCid> 0
- Then
- Update table1;
- Else
- Insert table1;
- EndIf;
- Insert table2 (field) values (id, cid, value );
- Commit;
- Exception
- When others then
- Rollback;
- End;
- ";
SQL = string. format (SQL, parameter); then excutesql (SQL );
Shame. In order to be a high-level programmer, this writing must be corrected.
The create procedure syntax in Oracle is as follows:
- Create [or replace] procedure procedure_name
- [(Parameter_name )[In|Out|In Out] Type, [...]
- Begin
- Procedure body
- End procedure_name
Or replace if the name already exists;
Procedure_name process name;
Parameter_name parameter name;
Type parameter type;
In | out | in out, default value of in. The parameter value does not change during running. The value of out is only assigned during running. in out can be assigned either in advance or in running;
Procedure_body process entity.
The subsequent code must follow the object-oriented idea and use the unique functions, processes, functions, and triggers of the database. Database and program separation is required.