Oracle 存储过程学习
Oracle 存储过程 学习 目录 Oracle 存储过程 1 Oracle 存储过程基础知识 1 Oracle 存储过程的基本语法 2 关于 Oracle 存储过程的若干问题备忘 4 1. 在 Oracle 中,数据表别名不能加 as 。 4 2. 在存储过程中, select 某一字段时,后面必须紧跟 into ,如果
Oracle 存储过程学习
目录
Oracle 存储过程 1
Oracle存储过程基础知识 1
Oracle存储过程的基本语法 2
关于Oracle存储过程的若干问题备忘 4
1. 在Oracle中,数据表别名不能加as。 4
2. 在存储过程中,select某一字段时,后面必须紧跟into,如果select整个记录,利用游标的话就另当别论了。 5
3. 在利用select...into...语法时,必须先确保数据库中有该条记录,否则会报出"no data found"异常。 5
4. 在存储过程中,别名不能和字段名称相同,否则虽然编译可以通过,但在运行阶段会报错 5
5. 在存储过程中,关于出现null的问题 5
6. Hibernate调用Oracle存储过程 6
用Java调用Oracle存储过程总结 6
一、 无返回值的存储过程 6
二、 有返回值的存储过程(非列表) 8
三、 返回列表 9
在存储过程中做简单动态查询 11
一、 本地动态SQL 12
二、 使用DBMS_SQL包 13
Oracle存储过程调用Java方法 16
Oracle高效分页存储过程实例 17
Oracle存储过程基础知识
商业规则和业务逻辑可以通过程序存储在Oracle中,这个程序就是存储过程。
存储过程是SQL, PL/SQL, Java 语句的组合,它使你能将执行商业规则的代码从你的应用程序中移动到数据库。这样的结果就是,代码存储一次但是能够被多个程序使用。
要创建一个过程对象(procedural object),必须有 CREATE PROCEDURE 系统权限。如果这个过程对象需要被其他的用户schema 使用,那么你必须有 CREATE ANY PROCEDURE 权限。执行 procedure 的时候,可能需要excute权限。或者EXCUTE ANY PROCEDURE 权限。如果单独赋予权限,如下例所示:
grant execute on MY_PROCEDURE to Jelly
调用一个存储过程的例子:
execute MY_PROCEDURE( 'ONE PARAMETER');
存储过程(PROCEDURE)和函数(FUNCTION)的区别。
function有返回值,并且可以直接在Query中引用function和或者使用function的返回值。
本质上没有区别,都是 PL/SQL 程序,都可以有返回值。最根本的区别是: 存储过程是命令, 而函数是表达式的一部分。比如:
select max(NAME) FROM
但是不能 exec max(NAME) 如果此时max是函数。
PACKAGE是function,procedure,variables 和sql 语句的组合。package允许多个procedure使用同一个变量和游标。
创建 procedure的语法:
CREATE [ OR REPLACE ] PROCEDURE [ schema.]procedure [(argument [IN | OUT | IN OUT ] [NO COPY] datatype [, argument [IN | OUT | IN OUT ] [NO COPY] datatype]... )] [ authid { current_user | definer }] { is | as } { pl/sql_subprogram_body | language { java name 'String' | c [ name, name] library lib_name }] |
Sql 代码:
CREATE PROCEDURE sam.credit (acc_no IN NUMBER, amount IN NUMBER) AS BEGIN UPDATE accounts SET balance = balance + amount WHERE account_id = acc_no; END; |
可以使用 create or replace procedure 语句, 这个语句的用处在于,你之前赋予的execute权限都将被保留。
IN, OUT, IN OUT用来修饰参数。
IN 表示这个变量必须被调用者赋值然后传入到PROCEDURE进行处理。
OUT 表示PROCEDURE 通过这个变量将值传回给调用者。
IN OUT 则是这两种的组合。
authid代表两种权限:
定义者权限(difiner right 默认),执行者权限(invoker right)。
定义者权限说明这个procedure中涉及的表,视图等对象所需要的权限只要定义者拥有权限的话就可以访问。
执行者权限则需要调用这个 procedure的用户拥有相关表和对象的权限。
Oracle存储过程的基本语法
1. 基本结构
CREATE OR REPLACE PROCEDURE
存储过程名字 END 存储过程名字 |
2. SELECT INTO STATEMENT
将select查询的结果存入到变量中,可以同时将多个列存储多个变量中,必须有一条
记录,否则抛出异常(如果没有记录抛出NO_DATA_FOUND)
例子:
BEGIN |
3. IF 判断
IF V_TEST=1 THEN |
4. while 循环
WHILE V_TEST=1 LOOP |
5. 变量赋值
V_TEST := 123; |
6. 用for in 使用cursor
... |
7. 带参数的cursor
CURSOR C_USER(C_ID NUMBER) IS SELECT NAME FROM USER WHERE TYPEID=C_ID; |
8. 用pl/sql developer debug
连接数据库后建立一个Test WINDOW
在窗口输入调用SP的代码,F9开始debug,CTRL+N单步调试
9. Pl/Sql中执行存储过程
在sql*plus中:
declare
|
在SQL/PLUS中调用存储过程,显示结果:
SQL>set serveoutput on --打开输出 SQL>var info1 number; --输出1 SQL>var info2 number; --输出2 SQL>declare var1 varchar2(20); --输入1 var2 varchar2(20); --输入2 var3 varchar2(20); --输入2 BEGIN pro(var1,var2,var3,:info1,:info2); END; / SQL>print info1; SQL>print info2; |
注:在EXECUTE IMMEDIATE STR语句是SQLPLUS中动态执行语句,它在执行中会自动提交,类似于DP中FORMS_DDL语句,在此语句中str是不能换行的,只能通过连接字符"||",或着在在换行时加上"-"连接字符。
关于Oracle存储过程的若干问题备忘
1. 在Oracle中,数据表别名不能加as。
如:
select a.appname from appinfo a;--
正确
select a.appname from appinfo as a;-- 错误
也许,是怕和Oracle中的存储过程中的关键字as冲突的问题吧
2. 在存储过程中,select某一字段时,后面必须紧跟into,如果select整个记录,利用游标的话就另当别论了。
select af.keynode into kn
from APPFOUNDATION af
where af.appid=aid and af.foundationid=fid; -- 有into,正确编译
select af.keynode
from APPFOUNDATION af
where af.appid=aid and af.foundationid=fid;-- 没有into,编译报错,提示:Compilation Error: PLS-00428: an INTO clause is expected in this SELECT statement
3. 在利用select...into...语法时,必须先确保数据库中有该条记录,否则会报出"no data found"异常。
可以在该语法之前,先利用select count(*) from 查看数据库中是否存在该记录,如果存在,再利用select...into...
4. 在存储过程中,别名不能和字段名称相同,否则虽然编译可以通过,但在运行阶段会报错
select keynode into kn from APPFOUNDATION where appid=aid and foundationid=fid;
-- 正确运行
select af.keynode into kn from APPFOUNDATION af where af.appid=appid and af.foundationid=foundationid;
-- 运行阶段报错,提示:
ORA-01422:exact fetch returns more than requested number of rows
5. 在存储过程中,关于出现null的问题
假设有一个表A,定义如下:
create table A( |
如果在存储过程中,使用如下语句:
select sum(vcount) into fcount from A where bid='xxxxxx';
如果A表中不存在bid="xxxxxx"的记录,则fcount=null(即使fcount定义时设置了默认值,如:fcount number(8):=0依然无效,fcount还是会变成null),这样以后使用fcount时就可能有问题,所以在这里最好先判断一下:
if fcount is null then
fcount:=0;
end if;
这样就一切ok了。
6. Hibernate调用Oracle存储过程
this.pnumberManager.getHibernateTemplate().execute( new HibernateCallback() ...{ public Object doInHibernate(Session session) throws HibernateException, SQLException ...{ CallableStatement cs = session .connection() .prepareCall("{call modifyapppnumber_remain(?)}"); cs.setString(1, foundationid); cs.execute(); return null; } }); |
用Java调用Oracle存储过程总结
一、 无返回值的存储过程
测试表:
-- Create table create table TESTTB ( ID VARCHAR2(30), NAME VARCHAR2(30) ) tablespace BOM pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited ); |
例: 存储过程为(当然了,这就先要求要建张表TESTTB,里面两个字段(I_ID,I_NAME)。
):
CREATE OR REPLACE PROCEDURE TESTA(PARA1 IN VARCHAR2, PARA2 IN VARCHAR2) AS BEGIN INSERT INTO BOM.TESTTB(ID, NAME) VALUES (PARA1, PARA2); END TESTA; |
在Java里调用时就用下面的代码:
package com.yiming.procedure.test;
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
public class TestProcedureDemo1 { public TestProcedureDemo1() { }
public static void main(String[] args) { String driver = "Oracle.jdbc.driver.OracleDriver"; String strUrl = "jdbc:Oracle:thin:@10.20.30.30:1521:vasms"; Statement stmt = null; ResultSet rs = null; Connection conn = null; CallableStatement proc = null; try { Class.forName(driver); conn = DriverManager.getConnection(strUrl, "bom", "bom"); proc = conn.prepareCall("{ call BOM.TESTA(?,?) }"); proc.setString(1, "100"); proc.setString(2, "TestOne"); proc.execute(); } catch (SQLException ex2) { ex2.printStackTrace(); } catch (Exception ex2) { ex2.printStackTrace(); } finally { try { if (rs != null) { rs.close(); if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } } catch (SQLException ex1) { } } } } |
二、 有返回值的存储过程(非列表)
例:存储过程为:
CREATE OR REPLACE PROCEDURE TESTB(PARA1 IN VARCHAR2, PARA2 OUT VARCHAR2) AS BEGIN SELECT NAME INTO PARA2 FROM TESTTB WHERE ID = PARA1; END TESTB; |
在Java里调用时就用下面的代码:
package com.yiming.procedure.test;
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types;
public class TestProcedureDemo2 { public static void main(String[] args) { String driver = "Oracle.jdbc.driver.OracleDriver"; String strUrl = "jdbc:Oracle:thin:@10.20.30.30:1521:vasms"; Statement stmt = null; ResultSet rs = null; Connection conn = null; CallableStatement proc = null; try { Class.forName(driver); conn = DriverManager.getConnection(strUrl, "bom", "bom"); proc = conn.prepareCall("{ call BOM.TESTB(?,?) }"); proc.setString(1, "100"); proc.registerOutParameter(2, Types.VARCHAR); proc.execute(); String testPrint = proc.getString(2); System.out.println("=testPrint=is=" + testPrint); } catch (SQLException ex2) { ex2.printStackTrace(); } catch (Exception ex2) { ex2.printStackTrace(); } finally { try { if (rs != null) { rs.close(); if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } } catch (SQLException ex1) { } } } } |
注意,这里的proc.getString(2)中的数值2并非任意的,而是和存储过程中的out列对应的,如果out是在第一个位置,那就是proc.getString(1),如果是第三个位置,就是proc.getString(3),当然也可以同时有多个返回值,那就是再多加几个out参数了。
三、 返回列表
由于Oracle存储过程没有返回值,它的所有返回值都是通过out参数来替代的,列表同样也不例外,但由于是集合,所以不能用一般的参数,必须要用pagkage了.所以要分两部分,
1. 建一个程序包。如下:
CREATE OR REPLACE PACKAGE TESTPACKAGE AS TYPE TEST_CURSOR IS REF CURSOR; end TESTPACKAGE; |
2. 建立存储过程,存储过程为:
CREATE OR REPLACE PROCEDURE TESTC(P_CURSOR out TESTPACKAGE.TEST_CURSOR) IS BEGIN OPEN P_CURSOR FOR SELECT * FROM BOM.TESTTB; END TESTC; |
可以看到,它是把游标(可以理解为一个指针),作为一个out 参数来返回值的。
在Java里调用时就用下面的代码:
在这里要注意,在执行前一定要先把Oracle的驱动包放到class路径里,否则会报错的。
package com.yiming.procedure.test;
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
public class TestProcedureDemo3 { public static void main(String[] args) { String driver = "Oracle.jdbc.driver.OracleDriver"; String strUrl = "jdbc:Oracle:thin:@10.20.30.30:1521:vasms"; Statement stmt = null; ResultSet rs = null; Connection conn = null; CallableStatement proc = null; try { Class.forName(driver); conn = DriverManager.getConnection(strUrl, "bom", "bom"); proc = conn.prepareCall("{ call bom.testc(?) }"); proc.registerOutParameter(1, Oracle.jdbc.OracleTypes.CURSOR); proc.execute(); rs = (ResultSet) proc.getObject(1);
while (rs.next()) { System.out.println(" + rs.getString(2) + " } } catch (SQLException ex2) { ex2.printStackTrace(); } catch (Exception ex2) { ex2.printStackTrace(); } finally { try { if (rs != null) { rs.close(); if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } } catch (SQLException ex1) { } } } } |
在存储过程中做简单动态查询
在存储过程中做简单动态查询代码 ,例如: |
|
  |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



To query the Oracle tablespace size, follow the following steps: Determine the tablespace name by running the query: SELECT tablespace_name FROM dba_tablespaces; Query the tablespace size by running the query: SELECT sum(bytes) AS total_size, sum(bytes_free) AS available_space, sum(bytes) - sum(bytes_free) AS used_space FROM dba_data_files WHERE tablespace_

Data import method: 1. Use the SQLLoader utility: prepare data files, create control files, and run SQLLoader; 2. Use the IMP/EXP tool: export data, import data. Tip: 1. Recommended SQL*Loader for big data sets; 2. The target table should exist and the column definition matches; 3. After importing, data integrity needs to be verified.

There are three ways to view instance names in Oracle: use the "sqlplus" and "select instance_name from v$instance;" commands on the command line. Use the "show instance_name;" command in SQL*Plus. Check environment variables (ORACLE_SID on Linux) through the operating system's Task Manager, Oracle Enterprise Manager, or through the operating system.

Creating an Oracle table involves the following steps: Use the CREATE TABLE syntax to specify table names, column names, data types, constraints, and default values. The table name should be concise and descriptive, and should not exceed 30 characters. The column name should be descriptive, and the data type specifies the data type stored in the column. The NOT NULL constraint ensures that null values are not allowed in the column, and the DEFAULT clause specifies the default values for the column. PRIMARY KEY Constraints to identify the unique record of the table. FOREIGN KEY constraint specifies that the column in the table refers to the primary key in another table. See the creation of the sample table students, which contains primary keys, unique constraints, and default values.

Uninstall method for Oracle installation failure: Close Oracle service, delete Oracle program files and registry keys, uninstall Oracle environment variables, and restart the computer. If the uninstall fails, you can uninstall manually using the Oracle Universal Uninstall Tool.

Oracle View Encryption allows you to encrypt data in the view, thereby enhancing the security of sensitive information. The steps include: 1) creating the master encryption key (MEk); 2) creating an encrypted view, specifying the view and MEk to be encrypted; 3) authorizing users to access the encrypted view. How encrypted views work: When a user querys for an encrypted view, Oracle uses MEk to decrypt data, ensuring that only authorized users can access readable data.

There are the following methods to get time in Oracle: CURRENT_TIMESTAMP: Returns the current system time, accurate to seconds. SYSTIMESTAMP: More accurate than CURRENT_TIMESTAMP, to nanoseconds. SYSDATE: Returns the current system date, excluding the time part. TO_CHAR(SYSDATE, 'YYY-MM-DD HH24:MI:SS'): Converts the current system date and time to a specific format. EXTRACT: Extracts a specific part from a time value, such as a year, month, or hour.

An AWR report is a report that displays database performance and activity snapshots. The interpretation steps include: identifying the date and time of the activity snapshot. View an overview of activities and resource consumption. Analyze session activities to find session types, resource consumption, and waiting events. Find potential performance bottlenecks such as slow SQL statements, resource contention, and I/O issues. View waiting events, identify and resolve them for performance. Analyze latch and memory usage patterns to identify memory issues that are causing performance issues.
