oracle存储过程函数汇总().docx

合集下载

oracle--存储过程--存储函数--触发器

oracle--存储过程--存储函数--触发器

存储过程和存储函数:指存储在数据库中供所有用户程序调用的子程序叫存储过程、存储函数。

语法:create [or replace] PROCEDURE 过程名(参数列表)ASPLSQL子程序体;存储过程实例:存储过程的调用:方法一:set serveroutput onbeginraisesalary(7369);end;/方法二:set serveroutput onexec raisesalary(7369);函数(Function)为一命名的存储程序,可带参数,并返回一计算值。

函数和过程的结构类似,但必须有一个RETURN子句,用于返回函数值。

函数说明要指定函数名、结果值的类型,以及参数类型等。

语法:CREATE [OR REPLACE] FUNCTION 函数名(参数列表)RETURN 函数值类型ASPLSQL子程序体;示例:函数的调用:declarev_sal number;beginv_sal:=queryEmpSalary(7934);dbms_output.put_line('salary is:' || v_sal);end;/在java语言中调用存储过程:存储过程:什么时候使用存储过程/存储函数?如果只有一个返回值,用存储函数;否则,就用存储过程。

在out参数中使用游标:声明包结构:创建包体:在Java语言中访问游标类型的out参数:触发器:数据库触发器是一个与表相关联的、存储的PL/SQL程序。

每当一个特定的数据操作语句(Insert,update,delete)在指定的表上发出时,Oracle自动地执行触发器中定义的语句序列。

触发器的类型语句级触发器在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行。

行级触发器(FOR EACH ROW)触发语句作用的每一条记录都被触发。

在行级触发器中使用old和new伪记录变量, 识别值的状态。

创建触发器:CREATE [or REPLACE] TRIGGER 触发器名{BEFORE | AFTER}{DELETE | INSERT | UPDATE [OF 列名]}ON 表名[FOR EACH ROW [WHEN(条件) ] ]PLSQL 块示例1:限制非工作时间向数据库插入数据示例二:确认数据(检查emp表中sal 的修改值不低于原值)运行效果:触发器的作用:触发器可用于数据确认实施复杂的安全性检查做审计,跟踪表上所做的数据操作等数据的备份和同步。

oracle函数调用存储过程

oracle函数调用存储过程

oracle函数调⽤存储过程1、⽆参数存储过程的调⽤--创建⽆参存储过程CREATE OR REPLACE FUNCTION stu_proc RETURN VARCHAR2IS--声明语句段v_name varchar2(20);BEGIN--执⾏语句段SELECT o.sname INTO v_name FROM student o where o.id=1;RETURN v_name;END;--调⽤⽆参存储过程DECLAREBEGINDBMS_OUTPUT.put_line('在PL/SQL中打印的结果:'||stu_proc);END;2、⼊参存储过程的调⽤--创建⼊参存储过程CREATE OR REPLACE FUNCTION stu_proc(v_id IN NUMBER) RETURN VARCHAR2IS--声明语句段v_name varchar2(20);BEGIN--执⾏语句段SELECT o.sname INTO v_name FROM student o where o.id=v_id;RETURN v_name;END;--调⽤⼊参存储过程DECLAREBEGINDBMS_OUTPUT.put_line('在PL/SQL中打印的结果:'||stu_proc(1));END;3、出参存储过程的调⽤--创建出参存储过程CREATE OR REPLACE FUNCTION stu_proc(v_name OUT VARCHAR2) RETURN VARCHAR2ISBEGIN--执⾏语句段SELECT o.sname INTO v_name FROM student o where o.id=2;RETURN v_name;END;--调⽤出参存储过程DECLAREv_name student.sname%type;BEGINDBMS_OUTPUT.put_line('在PL/SQL中打印的结果:'||stu_proc(v_name));END;4、出⼊参存储过程的调⽤--创建出⼊参存储过程CREATE OR REPLACE FUNCTION stu_proc(v_id IN NUMBER, v_name OUT VARCHAR2) RETURN VARCHAR2IS BEGIN--执⾏语句段SELECT o.sname INTO v_name FROM student o where o.id=v_id;RETURN v_name;END;--调⽤出⼊参存储过程DECLAREv_name VARCHAR2(20);BEGINDBMS_OUTPUT.put_line('在PL/SQL中打印的结果:'||stu_proc(1, v_name));END;。

Oracle数据库的函数,存储过程,程序包,游标,触发器

Oracle数据库的函数,存储过程,程序包,游标,触发器

Oracle数据库的函数,存储过程,程序包,游标,触发器Oracle⾃定义函数函数的主要特性是它必须返回⼀个值。

创建函数时通过 RETURN ⼦句指定函数返回值的数据类型。

函数的⼀些限制:●函数只能带有 IN 参数,不能带有 IN OUT 或 OUT 参数。

●形式参数必须只使⽤数据库类型,不能使⽤ PL/SQL 类型。

●函数的返回类型必须是数据库类型Create function 函数名称 return 返回值类型 asBegin····End 函数名称;--创建不带参数函数,返回t_book中书的数量create function getBookCount return number asbegindeclare book_count number;beginselect count(*) into book_count from t_book;return book_count;end;end getBookCount;--函数调⽤set serveroutput on;begindbms_output.put_line('表t_book中有'||getBookCount()||'本书');end;--创建带参数函数,查找某个表的记录数create function getTableCount(table_name varchar2) return number asbegindeclare recore_count number;query_sql varchar2(300);--定义sql语句beginquery_sql:='select count(*) from '||table_name;--execute immediate:⽴即执⾏该SQL语句execute immediate query_sql into recore_count;return recore_count;end;end getTableCount;--函数调⽤set serveroutput on;begindbms_output.put_line('表中有'||getTableCount('t_book_log')||'条数据');end;CREATE OR REPLACE FUNCTION item_price_rage (price NUMBER)/* 参数、指定返回类型 */RETURN varchar2AS/* 定义局部变量 */min_price NUMBER;max_price NUMBER;BEGINSELECT MAX(ITEMRATE), MIN(ITEMRATE) INTO max_price, min_priceFROM itemfile;IF price >= min_price AND price <= max_price THENRETURN '输⼊的单价介于最低价与最⾼价之间';ELSERETURN '超出范围';END IF;END;匿名块执⾏函数p NUMBER := 300;MSG varchar2(200);BEGINMSG := item_price_range(p);DBMS_OUTPUT.PUT_LINE(MSG);END;SELECT查询调⽤(因为函数必须有返回值)SELECT myfunction FROM dual;Oracle存储过程存储过程(Stored Procedure),就是⼀组⽤于完成特定功能的SQL语句集,该SQL语句集经过编译后存储在数据库中。

oracle存储过程 语法 函数 总结

oracle存储过程 语法 函数 总结

oracle存储过程语法函数总结对于oracle 存储过程是很优秀的一种脚本语言。

下面是一些整理:一,Plsql 调试存储过程:1、在oracle的配置和移植工具àNET MANAGER中配置连接2、在plsql中新建SQL窗口,编写存储过程3、在plsql中新建测试窗口,在begin end之间调用4、查看编译错误:在命令窗口中show errors procedure procedure_name 或者编辑的方式打开存储过程,在编译时会有错误提示一,Plsql 调试存储过程:1、在oracle的配置和移植工具àNET MANAGER中配置连接2、在plsql中新建SQL窗口,编写存储过程3、在plsql中新建测试窗口,在begin end之间调用4、查看编译错误:在命令窗口中show errors procedure procedure_name 或者编辑的方式打开存储过程,在编译时会有错误提示二,oracle存储过程基本语法1、 oracle存储过程结构:CREATE OR REPLACE PROCEDURE 存储过程名(输入输出参数)IS变量定义BEGIN代码;END 存储过程名;2、 if语句:If 逻辑表达式thenEnd;End if;If 逻辑表达式then BeginEnd;ElseBeginEnd;End if;If 逻辑表达式then BeginEnd;Elseif 逻辑表达式then BeginElseBeginEnd;End if;3、 For循环For in loop…End loop;E.g:CREATE OR REPLACE PROCEDURE TEST isBEGINfor i in 1..100 LOOPDBMS_OUTPUT.put_line(i);end LOOP;END TEST;注:这里的i可以不用申明,并且在循环体中,i会自增4、 while循环While 条件语句loopBeginEnd;End LOOP;E.g:CREATE OR REPLACE PROCEDURE TESTisi int := 1;BEGINwhile i < 100 LOOPDBMS_OUTPUT.put_line(i);end LOOP;END TEST;注:这里的i需要申明,并且循环体中,要对i进行改变5、游标的使用:定义游标打开游标提取数据关闭游标E.g:CREATE OR REPLACE PROCEDURE TESTisv_fid nvarchar2(80);Cursor cur_test isselect fid from t_pm_user;--定义游标open cur_test;--打开游标if cur_test%notfoundthen --判断游标中数据是否为空rollback;end if;loop--循环游标fetchcur_test into v_fid;--提取游标数据DBMS_OUTPUT.put_line(v_fid);EXITWHEN cur_test%NOTFOUND; --游标数据为空后退出循环end loop;close cur_test;--关闭游标END TEST;三,oracle与sqlserver部分差异1、常用函数差异Ø绝对值S:select abs(-1) valueO:select abs(-1) value from dualØ取整(大)S:select ceiling(-1.001) valueO:select ceil(-1.001) value from dualØ取整(小)S:select floor(-1.001) valueO:select floor(-1.001) value from dual Ø取整(截取)S:select cast(-1.002 as int) valueO:select trunc(-1.002) value from dual Ø四舍五入S:select round(1.23456,4) value 1.23460O:select round(1.23456,4) value from dual 1.2346Ø取随机数S:select rand() valueO:select sys.dbms_random.value(0,1) value from dual Ø如何处理null值(F2中的null以10代替)S:select F1,IsNull(F2,10) value from TblO:select F1,nvl(F2,10) value from TblØ连接S:select '11'+'22' valueO:select CONCAT('11','22') value from dualØ子串位置--返回3S:select CHARINDEX('s','sdsq',2) valueO:select INSTR('sdsq','s',2) value from dualØ求子串S:select substring('abcd',2,2) valueO:select substr('abcd',2,2) value from dualØ子串代替返回aijklmnefS:SELECT STUFF('abcdef', 2, 3, 'ijklmn') valueO:SELECT Replace('abcdef', 'bcd', 'ijklmn') value from dual Ø子串全部替换S:没发现O:select Translate('fasdbfasegas','fa','我' ) value from dual Ø长度S:len,datalengthO:lengthØ左补空格(LPAD的第一个参数为空格则同space函数)S:select space(10)+'abcd' valueO:select LPAD('abcd',14) value from dualØ右补空格(RPAD的第一个参数为空格则同space函数)S:select 'abcd'+space(10) valueO:select RPAD('abcd',14) value from dualØ删除空格S:ltrim,rtrimO:ltrim,rtrim,trimØ系统时间S:select getdate() valueO:select sysdate value from dualØ求日期S:select convert(char(10),getdate(),20) valueO:select trunc(sysdate) value from dualselect to_char(sysdate,'yyyy-mm-dd') value from dual Ø求时间S:select convert(char(8),getdate(),108) valueO:select to_char(sysdate,'hh24:mm:ss') value from dual Ø字符串转时间S:可以直接转或者select cast('2004-09-08'as datetime) valueO:SELECT To_date('2004-01-05 22:09:38','yyyy-mm-dd hh24-mi-ss') vaule FROMDUALØ求两日期某一部分的差(比如秒)S:select datediff(ss,getdate(),getdate()+12.3) valueO:直接用两个日期相减(比如d1-d2=12.3)SELECT (d1-d2)*24*60*60 vaule FROM DUALØ根据差值求新的日期(比如分钟)S:select dateadd(mi,8,getdate()) valueO:SELECT sysdate+8/60/24 vaule FROM DUAL2、其它差异Ø返回记录集S:直接在存储过程中用select即可O:一般在参数中定义一个游标类型的输出参数,在过程体中用open 游标名称for select 的方式返回记录集Ø代码格式S:语句结尾不用加分号O:语句结尾需要加分号Ø临时表S:一般动态创建临时表,临时表是一种”内存表”,不用后会自动删除表结构O:提前创建好临时表,oracle中临时表保存的是一个会话或者事务的数据,当断开连接或事务提交回滚后,临时表中的数据自动清空(清空的只是当前会话的临时表数据),但表结构还存在。

oracle 存储过程函数汇总

oracle 存储过程函数汇总
2011年01月14日 星期五 下午 8:43
一、DUMP()函数
DUMP(w[,x[,y[,z]]])
【功能】返回数据类型、字节长度和在内部的存储位置.
【参数】
w为各种类型的字符串(如字符型、数值型、日期型……)
x为返回位置用什么方式表达,可为:8,10,16或17,分别表示:8/10/16进制和字符型,默认为10。
语法: TRANSLATE(string,from_str,to_str)
功能: 返回将所出现的from_str中的每个字符替换为to_str中的相应字符以后的string. TRANSLATE是REPLACE所提供的功能的一个超集.
如果from_str比to_str长,那么在from_str中而不在to_str中而外的字符将从string中被删除,因为它们没有相应的替换字符. to_str不能为空
功能: 返回string的声音表示形式.这对于比较两个拼写不同但是发音类似的单词而言很有帮助.
使用位置:过程性语句和SQL语句。
12、SUBSTR
语法: SUBSTR(string,a[,b])
功能: 返回从字母为值a开始b个字符长的string的一个子字符串.如果a是0,那么它就被认为从第一个字符开始.如果是正数,返回字符是从左
使用位置:过程性语句和SQL语句。
5、NLS_INITCAP
语法:NLS_INITCAP(string[,nlsparams])
功能:返回字符串每个单词第一个字母大写而单词中的其他字母小写的string,nlsparams
指定了不同于该会话缺省值的不同排序序列。如果不指定参数,则功能和INITCAP相同。Nlsparams可以使用的形式是:

Oracle存储过程和自定义函数

Oracle存储过程和自定义函数

存储过程、存储函数概述存储过程和存储函数指存储在数据库中供所有用户程序调用的子程序叫存储过程、存储函数。

存储过程和存储函数的相同点:完成特定功能的程序。

存储过程和存储函数的不同点:存储函数可以用return语句返回,存储过程不能用return 语句返回。

存储过程的创建和调用创建和使用存储过程语法:create [or replace] procedure 过程名(参数列表) --or replace替换一个存储过程as --声明部分,同declare同一个意思plsql子程序体;注意:当程序体执行完之后在plsql当中会有一个存储数据库对象。

例子:使用存储过程打印hellowordcreate or replace procedure sayhellowordas 说明部分begindbms_output.put_line('helloword');end;/调用存储过程:方法1、exec syhellloword();方法2、beginsayhelloworld();sayhelloworld();end;/通过sqlplus调用存储过程打印出结果带参数的存储过程创建带参数的存储过程给指定员工涨100工资,并且打印涨前涨后的薪水实例:create or replace procedure raisesala(eno in number) --in为输入参数as --声明部分psal emp.sal%type; --声明变量begin--查询员工涨前薪水select psal into sal from emp where empno = eno;--修改员工薪水加100update emp set sal = sal +100 where empno = eno;--打印涨前和涨后的薪水dbms_output.put_line('涨前'||psal||'涨后'psal+100)end;/--结果输出,打开sqlplus通过如下语法执行进行修改薪水beginraisesala(7839); --括号内的值为打印输入的人员编号raisesala(7566);commit; --因为提交过事务,所以需要使用commit进行结束end;/执行后结果:。

oracle存储过程和函数例子

oracle存储过程和函数例子

oracle存储过程和函数例⼦关于游标if,for的例⼦create or replace procedure peace_ifiscursor var_c is select*from grade;beginfor temp in var_c loopif temp.course_name ='OS'thendbms_output.put_line('Stu_name = '||temp.stu_name);elsif temp.course_name ='DB'thendbms_output.put_line('DB');elsedbms_output.put_line('feng la feng la ');end if;end loop;end;---关于游标 for,case 的例⼦1create or replace procedure peace_case1iscursor var_c is select*from test_case;beginfor temp in var_c loopcase temp.volwhen1thendbms_output.put_line('haha1');when2thendbms_output.put_line('haha2');when3thendbms_output.put_line('haha3');when4thendbms_output.put_line('haha4');elsedbms_output.put_line('qita');end case ;end loop;end;---关于游标 for,case 的例⼦2create or replace procedure peace_case2iscursor var_c is select*from test_case;beginfor temp in var_c loopcasewhen temp.vol=1thendbms_output.put_line('haha1');when temp.vol=2thendbms_output.put_line('haha2');when temp.vol=3thendbms_output.put_line('haha3');when temp.vol=4thendbms_output.put_line('haha4');elsedbms_output.put_line('qita');end case ;end loop;end;---关于for 循环的例⼦create or replace procedure peace_forissum1 number :=0;temp varchar2(500);beginfor i in1..9 looptemp :='';for j in1 .. iloopsum1 := i * j;temp :=temp||to_char(i) ||' * '||to_char(j) ||' = '||to_char(sum1) ||'';end loop;dbms_output.put_line(temp );end loop;end;---关于 loop循环的例⼦create or replace procedure peace_loopissum1 number :=0;temp number :=0 ;beginloopexit when temp>=10 ;sum1 := sum1+temp;temp :=temp+1;end loop;dbms_output.put_line(sum1 );end;---关于游标和loop循环的例⼦create or replace procedure loop_curisstu_name varchar2(100);course_name varchar2(100);cursor var_cur is select*from grade ;beginopen var_cur;loopfetch var_cur into stu_name,course_name;exit when var_cur%notfound;dbms_output.put_line(stu_name|| course_name);end loop;close var_cur;end;---关于异常处理的例⼦create or replace procedure peace_exp(in1 in varchar2)isc_n varchar2(100);beginselect course_name into c_n from grade where stu_name = in1; dbms_output.put_line(c_n);exceptionwhen no_data_foundthendbms_output.put_line('try');when TOO_MANY_ROWSthendbms_output.put_line('more');end;---关于异常处理的例⼦2create or replace procedure peace_insert ( c_n in varchar2)iserror EXCEPTION;beginif c_n ='OK'theninsert into course (course_name) values (c_n);elsif c_n ='NG'theninsert into course (course_name) values (c_n);raise error;elseDbms_Output.put_line('c_n'|| c_n);end if;commit;exceptionwhen error thenrollback;Dbms_Output.put_line('ERRO');end;---关于包的例⼦定义包create or replace package peace_pkgasfunction test1(in1 in varchar2)return number;procedure test2 (in2 in varchar2);end peace_pkg;---关于包的例⼦定义包体create or replace package body peace_pkgasfunction test1(in1 in varchar2)return numberastemp number;begintemp :=0;return temp;end;procedure test2 (in2 in varchar2)isbegindbms_output.put_line(in2);end;end peace_pkg;。

oracle函数列表word版

oracle函数列表word版

oracle函数列表word版pl/sql单行函数和组函数详解函数是具有零个或多个参数和一个返回值的程序。

在SQL中,Oracle构建了一系列函数,这些函数可以称为SQL或PL/SQL语句。

功能主要分为两类:单线功能;组函数本文将讨论如何使用单行函数和使用规则。

SQL中的单行函数sql和pl/sql中自带很多类型的函数,有字符、数字、日期、转换、和混合型等多种函数用于处理单行数据,因此这些都可被统称为单行函数。

这些函数均可用于select,where、orderby等子句中,例如下面的例子中就包含了to_char,upper,soundex 等单行函数。

从EmpWhereUpper(ename)中选择ename、to_uchar(hiredate,'day,dd mon yyyy'),如'al%'orderbysoundex(ename)单行函数也可以在其他语句中使用,如update的set子句,insert的values子句,delet的where子句,认证考试特别注意在select语句中使用这些函数,所以我们的注意力也集中在select语句中。

null和单行函数很难从如何理解null开始,即使是非常有经验的人也仍然对它感到困惑。

空值表示未知数据或空值。

如果算术运算符的任何操作数为空,则结果将为空值。

这条规则也适用于许多功能。

调用null参数时,只有concat、decode、dump、NVL和replace可以返回非null值。

其中,NVL函数是最重要的,因为它可以直接处理空值。

NVL有两个参数:NVL(x1,x2),x1和x2都是表达式。

当X1为空时,返回X2,否则返回X1。

现在让我们看一下EMP数据表,包括工资和奖金,总的补偿需要计算。

columnnameemp_idsalarybonuskeytypepknulls/uniquenn,unnfktabledatatypenumbernum bernumberlength11.211.2如果一行为空,结果将为空,而不是简单地将工资和奖金相加。

oracle存储过程与函数

oracle存储过程与函数

Oracle存储过程与函数▲▲存储过程:create procedure pro_helloisname varchar2(20):='张三';begindbms_output.put_line('Hello World!'||name);end;******************************************************************************* create or replace procedure pro_hello(name varchar --参数中数据类型不能有长度)isname1 varchar2(20); --定义变量时,数据类型一定需要规定长度,这里没有字符串的长度会出错begindbms_output.put_line('Hello World!'||name);end;/调用:declarename1 varchar2(20):='&名字';beginpro_hello(name1);end;/--variable a varchar2(20); --声明一个变量aexec :a :='zhangsan'; --向变量a中赋值exec pro_hello(:a);******************************************************************************* create or replace procedure pro_hello(name in varchar --参数的类型有三种--in 输入类型的参数,默认的时候类型是in类型--out 输出类型的参数--in out既输入,又输出的参数)isname1 varchar2(20); --定义变量时,数据类型一定需要规定长度,这里没有字符串的长度会出错begindbms_output.put_line('Hello World!'||name);end;/******************************************************************************* --根据员工编号查询员工名称create or replace procedure pro_findEmpNameById(p_empno in emp.empno%type,p_ename out emp.ename%type --out 类型的参数可以在过程内部当作变量使用)isbeginselect ename into p_ename from emp where empno=p_empno;end;/调用:declarev_ename emp.ename%type;beginpro_findEmpNameById(7369,v_ename);dbms_output.put_line('编号7369对应的员工名称是'||v_ename);end;/*******************************************************************************▲▲函数:create or replace function getEnameById(p_empno in emp.empno%type)returnemp.ename%typeisv_ename emp.ename%type;beginselect ename into v_ename from empwhere empno=p_empno;dbms_output.put_line('恭喜你,'||p_empno||'编号所对应的员工是'||v_ename);return v_ename;exceptionwhen no_data_found thendbms_output.put_line('没有编号'||p_empno||'所对应的员工!');when too_many_rows thendbms_output.put_line('查询出的数据多余一条!');when others thendbms_output.put_line('未知异常,请速与管理员联系');end;/调用:declarev_empno emp.empno%type:=7900;v_ename emp.ename%type;beginv_ename := getEnameById(v_empno);dbms_output.put_line('外部调用函数得到的返回名称是'||v_ename);end;/******************************************************************************* create or replace function getWorkDays(p_empno in emp.empno%type)returnnumberisdays number;beginselect sysdate-hiredate into days from emp where empno=p_empno;return days;exceptionwhen no_data_found thendbms_output.put_line('没有编号'||p_empno||'所对应的员工!');when others thendbms_output.put_line('未知异常,请速与管理员联系');end;/调用:declarev_days number;v_empno emp.empno%type:=7900;beginv_days := getWorkDays(v_empno);dbms_output.put_line(v_empno||'编号对应的工作天数是'||round(v_days));end;/。

存储过程常用函数总结(不定期更新)

存储过程常用函数总结(不定期更新)

存储过程常用函数总结(不定期更新)存储过程是一组预定义的SQL语句集合,可以接受参数并返回结果。

在存储过程中,我们可以使用许多常用的函数来处理和转换数据。

下面是一些常用函数的总结:1.字符串处理函数-CONCAT:用于合并两个或多个字符串。

-SUBSTRING:用于提取字符串的一部分。

-REPLACE:用于替换字符串中的指定字符。

-CHAR_LENGTH:用于计算字符串的长度。

-UPPER/LOWER:用于将字符串转换为大写/小写。

-TRIM:用于去除字符串首尾的空格。

2.数值处理函数-ROUND:用于将数值四舍五入到指定的小数位数。

-FLOOR/CEILING:用于向下/向上取整。

-ABS:用于计算数值的绝对值。

-MOD:用于计算两个数值的模运算结果。

-RAND:用于生成随机数。

3.日期和时间处理函数-NOW:用于获取当前的日期和时间。

-DATE_FORMAT:用于将日期格式化为指定的格式。

-DATEDIFF:用于计算两个日期之间的天数差。

-DAY/WEEK/MONTH/YEAR:用于提取日期的天/周/月/年。

-ADDDATE/DATE_ADD:用于对日期进行加法运算。

-SUBDATE/DATE_SUB:用于对日期进行减法运算。

4.条件处理函数-IF:用于实现条件判断。

-CASE:用于根据不同的条件执行不同的操作。

-COALESCE:用于返回第一个非NULL值。

-NULLIF:用于判断两个表达式是否相等,若相等则返回NULL。

5.聚合函数-SUM:用于计算指定列的总和。

-AVG:用于计算指定列的平均值。

-COUNT:用于计算指定列的行数。

-MIN/MAX:用于计算指定列的最小/最大值。

-GROUP_CONCAT:用于将指定列的值连接为一个字符串。

6.数据类型转换函数-CAST/CONVERT:用于将一个数据类型转换为另一个数据类型。

-STR_TO_DATE:用于将字符串转换为日期类型。

-DATE_FORMAT:用于将日期类型转换为字符串。

ORACLE存储过程,函数,包,游标

ORACLE存储过程,函数,包,游标

ORACLE存储过程,函数,包,游标1、 PL/SQL语句块PL/SQL语句块只适⽤于Oracle数据库,使⽤时临时保存在客户端,⽽不是保存在数据库。

基本语法:Sql代码1. declare2. 变量声明、初始化3. begin4. 业务处理、逻辑代码5. exception6. 异常捕获7. end;变量声明:<变量名> <类型及长度> [:=<初始值>]例:v_name varchar2(20):=’张三’;2、循环语句loop循环语法:Sql代码1. loop2. exit when 表达式3. end loop;while循环语法:Sql代码1. while 表达式2. loop3. end loop;for循环语法:Sql代码1. for <变量> in <变量取值范围(⼩值..⼤值,如1..100)> loop2. end loop;for循环的变量可不做声明及初始化。

3、 if判断语句基本语法:Sql代码1. if <表达式> then2. …3. else if <表达式> then4. …5. else6. …7. end if;8. end if;例:Sql代码1. declare2. v_identity number(4):=0;3. begin4. loop5. if v_identity=1 then6. dbms_output.put_line('v_identity=1');7. else if v_identity=3 then8. dbms_output.put_line('v_identity=3');9. else if v_identity=6 then10. exit;11. else12. dbms_output.put_line('v_identity is not 1 or 3');13. end if;14. end if;15. end if; -- 注意,有多少个if就要有多少个end if结束标志。

oracle存储过程和函数.docx

oracle存储过程和函数.docx

Oracle存储过程和函数一、存储过程过程:将一些内部联系的命令组成一个个过程,通过参数在过程Z间传递数据。

存储过程的特点:1、存储过程里的代码都己经被编译过。

可以直接执行。

使用吋无需编译,提高工作效率2、客户端通过调用存储过程,可以减少网络流量,加快了系统执行速度。

3、可以减少SQL注入,提高系统的安全性。

4、在同时进行主、从表及多表间的数据维护及有效性验证时,使用存储过程比较方便,而且可以有效利用SQL中的事务处理的机制;5、使用存储过程,可以实现存储过程设计和编码工作分开进行存储过程包含1、声明部分:在声明部分可以对不同数据类型的数据进行声明,包括类型、游标、常量、变量、界常等。

2、执行部分:主要是为了完成或者达到一个特定的1=1的或功能3、异常处理部分:在执行过程中,对于引发错误的操作,进行异常捉示。

Oracle中创建存储过程的语法:Create or replace procedure 存储过程名(参数1 in type,参数2 out type)As声明语句Begin执行语句Exception异常处理语句End;注意:1、存储过程参数不带取值范围,in表示传入,out表示输出2、as后的语句声明变量,并且变量有取值范围,后面加上分号3、begin关键字表示PL/SQL的开始4、exception关键字用来处理异常,异常信息常用raise +异常名的方式5、end关键字表示存储过程的结束预定义异常的简单描述asuname varchar(20);beginselect name into uname from test where id = 23;dbms output.put line(uname);带输入参数存储过程create or replace procedure test_proc(uid in number) asuname varcr'iar (20);beginselect name into uname from test where id = uid; dbms cmtput.put line(uname);exceptionwhen NO DATA FOUND thenRAISE APPLICATION ERROR(-20011, 'ERROR:不存在! *);end;带输出参数存储过程create or replace procedure test_proc(num out number) asbeginselect count(*) into num from test where id = 25; dbms output•put line(num); exceptionwhen NO DATA FOUND thenRAISE APPLICATION ERROR(-20011, 'ERROR:不存在!');end;带输出和输出参数存储过程create or replace procedure test_proc (uio umber z num out number)3 Suname varchar(20);beginselect name into uname from test where id = uid;select count (*) into num from test where id = 25;dbms_output.put_line (uname);dbms output.put line (num);when NO DATA FOUND t-ienRAISE APPLICATION ERROR (-20011, •ERROR:不存在!1 );存储过程的调用通过Call存储过程名称(参数);Begin存储过程名称(参数);End;二、函数Oracle屮的函数与存储过程类似,也是将一组能够实现特定功能的SQL或者PL/SQL 语句块组合在一起的程序集,并且能够将执行结果返冋。

oracle存储过程常用字符串处理函数

oracle存储过程常用字符串处理函数

oracle存储过程常用字符串处理函数在Oracle中,常用的字符串处理函数有:
1.CONCAT:用于连接两个或多个字符串。

2.SUBSTR:用于提取字符串的一部分。

3.INSTR:用于查找字符串中特定子串的位置。

4.REPLACE:用于替换字符串中的指定子串。

5.UPPER:用于将字符串转换为大写。

6.LOWER:用于将字符串转换为小写。

7.INITCAP:用于将字符串的首字母转换为大写,其余字母转换为小写。

8.TRIM:用于删除字符串首尾的空格或指定字符。

9.LENGTH:用于返回字符串的长度。

10.LPAD:用于在字符串的左侧填充指定字符,使字符串达到指定长度。

11.RPAD:用于在字符串的右侧填充指定字符,使字符串达到指定长度。

12.TO_CHAR:用于将其他数据类型转换为字符类型。

13.TO_NUMBER:用于将字符类型转换为数字类型。

14.TO_DATE:用于将字符类型转换为日期类型。

15.REGEXP_REPLACE:用于使用正则表达式替换字符串中的指定内容。

以上是一些常用的字符串处理函数,在实际的存储过程中可以根据具
体的需求,选择合适的函数来进行字符串处理。

Oracle的函数和存储过程

Oracle的函数和存储过程

Oracle的函数和存储过程【】主键就是区别这个表的唯一关键字比如一个学生表学号不能重复且唯一学号就是关键字(此时学号就可以作为主键)【】外键就是跟其他表联系的字段还是比如有一张学生表还有一张选课表这个时候要修改学生表中的学号选课表里对应的就也得变这样就需要给选课表加学号作为外键约束这样当你修改学号时所有外键关联的就都改了【】视图(VIEW)也被称作虚表,即虚拟的表,是一组数据的逻辑表示,其本质是对应于一条SELECT语句,结果集被赋予一个名字,即视图名字。

视图本身并不包含任何数据,它只包含映射到基表的一个查询语句,当基表数据发生变化,视图数据也随之变化。

【】在Java程序中设置事务处理setAutoCommit(false);不让其自动提交。

【函数:】①字符函数:lower(char):将字符串转化为小写的格式upper(char):将字符串转化为大写的格式length(char):返回字符串的长度substr(char,m,n):取字符串的子串写sql语句1分析清晰思路【replace函数】replace(char1,search_string,replace,)例子:select replace(ename,'A','我是老鼠')from emp;----->含义:把字段ename中凡是‘A’用'我是老鼠'替代。

【日期函数】sysdate 返回系统当前时间add_months 超过了指定月份的日期to_char 把其他的转换成字符串的函数【数据库的导入和导出】以.dmp的格式导出数据库到磁盘exp call_out/call_out@orcl owner=call_out file=d:\call_out.dmp导入数据库:(导入自己的表)imp userid=call_out/call_out@orcl tables=(emp) file=d:\xx.dmp【表空间】表空间是数据库的逻辑组成部分,数据库数据存放在数据文件中,表空间是由一个或多个数据文件组成的、【索引】可显著提高数据库的查询速度,比如char定长可以显著提高查询速度。

Oracle数据库---函数与存储过程.doc

Oracle数据库---函数与存储过程.doc

1.创建自定义函数Create or replace function 函数名return 返回值的类型as Begin函数定义End函数名;--- -------------- --- ---------------------- •「一 --------------------------- 丁---------------------------- - ・create or replace funcjtion getcount return number as bwgindeclare st_cou nt n umber;beginselect count⑴ into st_count from student;return st_count;end;end getcount;在下面的数据字典中可以查到。

SQL 输出统计農select object.nam已object_typ已status from user_objects where object_name=upper('getcou nt|);1| ▼ S M@ 幣[Sa lOBJECT-NAME|OBJECT.TYPE J STATUS |► 1GETCOUNT FUNCTION VALID2.调用自定义函数SQL 输出|统计表 begin dbms_output.putjine(getcou nt(»; end ; SQL 給出 统计豪3. 函数参数 Create or replace function 函数名(数据类型1 参数1,数据 类型2参数2, ....) return 返回值类型asBegin函数定义End 函数名SQL 給出|统计表drop function getcount|删除函数:4. 对于数据表student,如果需要获得有关该表的信息,如 表中的学生的名字,应该使用自定义函数,如果需要操作 表的数据,如更新某列的值,则需要使用存储过程。

oracle函数及存储过程教程

oracle函数及存储过程教程

u--常用变量类型1.binary_integer:整数,主要用来计数而不是用来表示字段类型2.number数字类型3.char定长字符串4.date日期5.long长字符串,最长2GG6.boolean类型:可以取值true、false、null,默认为null,declarev_ename emp.ename%type;v_sal emp.sal%type;beginselect ename,sal into v_ename,v_sal from emp where empno=7902;if v_ename is null thendbms_output.put_line('null');elsedbms_output.put_line(v_ename||' '||v_sal);end if;end;------------Record变量类型,相当于类------------------declaretype emp_record is record( v_ename emp.ename%type,v_sal emp.sal%type,v_empno emp.empno%type);v_emp emp_record;beginselect ename,sal,empno into v_emp from emp where empno=7902;dbms_output.put_line(v_emp.v_ename||','||v_emp.v_sal||','||v_emp.v_empno); end;------------------------------------declaretype test_record is record(v_ename emp.ename%type,v_sal emp.sal%type,v_loc dept.loc%type,v_dname dept.dname%type,v_deptno dept.deptno%type);v_test test_record;beginselect e.ename,e.sal,d.loc,d.dname,d.deptnointo v_test from emp e join dept don(e.deptno = d.deptno)where e.empno=7902;dbms_output.put_line(v_test.v_ename||','||v_test.v_sal);end;--使用%rowtype声明record变量----------------declarev_temp dept%rowtype;beginv_temp.deptno:=50;v_temp.dname:='yugang';v_temp.loc:='beijing';dbms_output.put_line(v_temp.deptno||''||v_temp.dname||''|| v_temp.loc);end;-----------------Table变量类型,相当于数组类型--------------------while循环------------declaretype type_table is table of number index by binary_integer;v_table type_table;v_index binary_integer;beginv_table(20) :=20;v_table(-1) :=-1;v_index := v_table.first;while v_index <=v_st loopdbms_output.put_line(v_table(v_index));v_index :=v_table.next(v_index);end loop;end;注: binary_integer表示数组下标值-------------for循环------------------declaretype type_table is table of number index by binary_integer;v_table type_table;beginv_table(0) :=20;v_table(1) :=21;v_table(2) :=22;v_table(3) :=23;for i in v_table.first .. v_st loopdbms_output.put_line(v_table(i));end loop;end;---------------------Cursor的使用-------------------DeclareCursor c isSelect * from emp;V_emp c%rowtype;BeginOpen c;Fetch c into v_emp;Dbms_output.put_line(v_emp.ename);Close c;End;-------------------Cursor+for循环使用----------declarecursor c isselect * from emp;beginfor v_emp in c loopdbms_output.put_line(v_emp.ename);end loop;end;---------------Cursor+when循环的使用----------------declarecursor emp_cur isselect ename from emp;v_name emp.ename%type;beginopen emp_cur;loopfetch emp_cur into v_name;exit when emp_cur%notfound;dbms_output.put_line(v_name);end loop;close emp_cur;end;---------------Cursor+while循环使用------------------------- declarecursor emp_cur isselect ename from emp;v_name emp.ename%type;beginopen emp_cur;fetch emp_cur into v_name;while (emp_cur%found) loopdbms_output.put_line(v_name||’’||cur%rowcount);fetch emp_cur into v_name;end loop;dbms_output.put_line(v_name);close emp_cur;end;注:%rowcount 表示第几个结束本次循环:Loop...if(true) thengoto nextloop;end if;...<<next_loop>>null;end loop;-----------------------Cursor的优化-------------------------------------declaretype emp_indtab is table of varchar2(20) index by binary_integer;v_emp emp_indtab;beginselect ename bulk collect into v_emp from emp;//将集合放在bulk collect 中for i in v_emp.first..v_st loopdbms_output.put_line(v_emp(i));end loop;end;------------------------------Cursor+bulk collect--------------------------declaretype emp_indtab is table of varchar2(20) index by binary_integer;v_emp emp_indtab;cursor emp_cur isselect ename from emp;beginopen emp_cur;fetch emp_cur bulk collect into v_emp limit 10;while v_emp.count > 0 loopfor i in v_emp.first..v_st loopdbms_output.put_line(v_emp(i));end loop;fetch emp_cur bulk collect into v_emp limit 10;end loop;endloopfetch emp_cur into ename,empno,sal,deptname;exit when emp_cur%notfound;+insert into bd_psndoc values(fun_pkpsndoc,ename,empno,sal,deptname);end loop;----------------------------插入记录类型数据--------------------------------- declaretype test_indtab is table of test%rowtype index by binary_integer;v_test test_indtab;beginv_test(1).num :='2001';v_test(1).name :='linqigang';v_test(2).num :='2002';v_test(2).name :='lin';v_test(3).num :='2003';v_test(3).name :='lingang';forall i in v_test.first ..v_stinsert into test valuesv_test(i);同于for i in v_test.first..v_st loopInsert into test valuest v_test(i);commit;end;注:红色部分为for循环的另一种形式专用于插入对DDL的操作Beginexecute immediate ‘drop table test’;End;---------------异常的处理---------------------------v_ename varchar2(20);beginselect ename into v_ename from emp where empno=1; dbms_output.put_line(v_ename);exceptionwhen no_data_found thendbms_output.put_line('no_data_found');when too_many_rows thendbms_output.put_line('too many');end;---------------------自定义异常------------------------------------ declaree1 exception;//定义异常v_n1 number;beginif v_n1 is null thenraise e1;//抛出异常end if;dbms_output.put_line('aa');exceptionwhen e1 then//捕获异常dbms_output.put_line('null');when othersdbms_output.put_line(‘others’);end;-------------------------------------------------------------------------- create table child(c1 number primary key,c2 number, foreign key (c2) references parent(c1));create table parent(c1 number primary key ,c2 number); -------------------------------------------------------------------------- declaree_noval exception;pragma exception_init(e_noval,-2291);insert into child values(1,2);exceptionwhen e_noval thendbms_output.put_line('no dept_id');end;------------------------存储过程----------------------------------------------查看存储过程源码desc user_source;select text form user_source where name='过程名大写';调用存储过程:exec xx 或者begin p; end;差看错误:show error;create or replace procedure proc1isbegindbms_output.put_line(d'hao');end;-----------------------带参数的存储过程-------------------------------------create or replace procedure proc(p_n1 varchar2,p_n2 out varchar2,p_n3 in out varchar2default=’10’)//default 缺省值isv_n1 varchar2(10);begin--p_n1 :=p_n1 ||'d';//注释掉v_n1 :=p_n1;p_n2 := p_n2||'d';p_n3 := p_n3||'d';dbms_output.put_line(v_n1);//avcdbms_output.put_line(p_n1);//avcdbms_output.put_line(p_n2);//ddbms_output.put_line(p_n3);//avcdend;调用上述存储过程:位置标识法declarev_n1 varchar2(10) :='avc';v_n2 varchar2(10) :='avc';v_n3 varchar2(10) :='avc';proc(v_n1,v_n2,v_n3);//位置标识法dbms_output.put_line(v_n1);avcdbms_output.put_line(v_n2);ddbms_output.put_line(v_n3);avcdend;总结: in ,或者无,可以传入,但不可以输出Out ,可以输出,不可以传入-----------------------函数创建-------------------------create or replace function fun1(p_id number)return numberisv_sal number(11,2);beginselect sal into v_sal from empwhere empno= p_id;return v_sal;end;----------------函数调用-----------------------Select fun1(7902) from dual;或者:BeginDbms_output.put_line(func1(7902)); end;-----------包Package------------------------------------------------ //包头create or replace package pkg1istype t_rec is record(c1 number,c2 number);v_rec t_rec;procedure proc1;function fun1 return number;end;//包体create or replace package body pkg1isprocedure proc1isbegindbms_output.put_line(1);end proc1;function fun1 return numberisbeginreturn 1;end fun1;end;------------------触发器,trigger-----------------------------trigger必须存储在数据库中对表的关联密切对于过程和函数必须显示的由另一个说明块调用trigger,是由触发事件自动激发(insert ,update,delete)注:有for each row 的是行级触发,create or replace trigger rigger_namebefore|after delete or update on student (for each row) //行级触发器,语句级触发器declarebegin.....endcreate table test(c1 number,c2 number);create or replace trigger t1before insert on test for each rowdeclarebeginselect s1.nextval into :new.c1 from dual;end;注::new 和:old 只能在行级触发器应用触发器不能写commit,rollback,savepointcreate or replace trigger taafter insert on A for each rowdeclarebegininsert into B values(:erid,:new.department);end;分页查询:create or replace package page_pkgistype myCursor is ref cursor;end;create or replace procedure page_pro(tableName varchar2,currentPage number,pageSize number,totalPages out number, totalRecordsout number,pageCursor out page_pkg.mycursor)isv_startRecord number;v_endRecord number;v_sql varchar2(100);beginv_startRecord :=(currentPage-1)*pagesize+1;v_endRecord :=currentPage*pageSize;v_sql := 'select * from (select e.* ,rownum rn from'|| tableName ||'ewhere rownum<'||v_endRecord||')where rn >='||v_startRecord;open pageCursor for v_sql;v_sql := 'select count(*) from '||tableName;execute immediate v_sql into totalRecords;if mod(totalRecords,pageSize)=0 thentotalPages :=totalRecords/pageSize;elsetotalPages :=totalRecords/pageSize+1;end if;end;declaretype emp_table is table of emp.ename%type index by binary_integer;test_table emp_table;type emp_cursor is ref cursor;my_cursor emp_cursor;v_index number :=1;beginopen my_cursor for select ename from emp;loopfetch my_cursor into test_table(v_index);exit when my_cursor%notfound;v_index := v_index+1;end loop;close my_cursor;v_index := v_index-1;for i in 1.. v_index loopdbms_output.put_line(test_table(i));exit when i=v_index;end loop;end;declaretype emp_record_type is record(myNo emp.empno%type,myName emp.ename%type);my_record emp_record_type;beginselect empno,ename into my_record from emp where empno=7788; dbms_output.put_line(my_record.myNo||' '||my_record.myName); end;createorreplaceprocedure up_bd_psndoc isename varchar2(20);empno varchar2(20);sal number(20);deptname varchar2(20);cursor emp_cur isselect ename,empno,sal,deptname from bd_emp;beginopen emp_cur;loopfetch emp_cur into ename,empno,sal,deptname;exit when emp_cur%notfound;+insert into bd_psndoc values(fun_pkpsndoc,ename,empno,sal,deptname);end loop;close emp_cur;commit;exceptionwhen too_many_rows thendbms_output.put_line('many');whenothersthendbms_output.put_line('other');end;。

oracle存储过程+函数语法

oracle存储过程+函数语法

存储过程1 CREATE OR REPLACE PROCEDURE 存储过程名2 IS3 BEGIN4 NULL;5 END;行1:CREATE OR REPLACE PROCEDURE 是一个SQL语句通知Oracle数据库去创建一个叫做skeleton存储过程, 如果存在就覆盖它;行2:IS关键词表明后面将跟随一个PL/SQL体。

行3:BEGIN关键词表明PL/SQL体的开始。

行4:NULL PL/SQL语句表明什么事都不做,这句不能删去,因为PL/SQL体中至少需要有一句;行5:END关键词表明PL/SQL体的结束存储过程创建语法:create or replace procedure 存储过程名(param1 in type,param2 out type)as变量1 类型(值范围); --vs_msg VARCHAR2(4000);变量2 类型(值范围);BeginSelect count(*) into 变量1 from 表A where列名=param1;If (判断条件) thenSelect 列名 into 变量2 from 表A where列名=param1;Dbms_output。

Put_line(‘打印信息’);Elsif (判断条件) thenDbms_output。

Put_line(‘打印信息’);ElseRaise 异常名(NO_DATA_FOUND);End if;ExceptionWhen others thenRollback;End;注意事项:存储过程参数不带取值范围,in表示传入,out表示输出类型可以使用任意Oracle中的合法类型。

2,变量带取值范围,后面接分号3,在判断语句前最好先用count(*)函数判断是否存在该条操作记录4,用select 。

into。

给变量赋值5,在代码中抛异常用 raise+异常名CREATE OR REPLACE PROCEDURE存储过程名(--定义参数is_ym IN CHAR(6) ,the_count OUT NUMBER, )AS--定义变量vs_msg VARCHAR2(4000); --错误信息变量vs_ym_beg CHAR(6); --起始月份vs_ym_end CHAR(6); --终止月份vs_ym_sn_beg CHAR(6); --同期起始月份vs_ym_sn_end CHAR(6); --同期终止月份--定义游标(简单的说就是一个可以遍历的结果集) CURSOR cur_1 IS SELECT 。

Oracle常用包、函数、存储过程

Oracle常用包、函数、存储过程

Oracle常用包、函数、存储过程Oracle常用包、存储过程、函数常用包、存储过程1 dbms_output作用:输入和输出信息,使用过程PUT和PUT_LINES可以将信息发送到缓冲区,使用过程GET_LINE和GET_LINES可以显示缓冲区信息。

1.1 enable该过程用于激活对过程PUT,PUT_LINE,GET_LINE,GET_LINES的调用。

语法如下:dbms_output.enable(buffer_size in integer default 20000);1.2 disable该过程用于禁止对过程PUT,PUT_LINE,GET_LINE,GET_LINES的调用。

语法如下:dbms_output.disable;1.3 put和put_line过程put_line用于将一个完整行的信息写入到缓冲区中,过程put则用地分块建立行信息,当使用过程put_line时,会自动在行的尾部追加行结束符;当使用过程put时,需要使用过程new_line追加行结束符。

示例如下:set serverout onbegindbms_output.put_line('伟大的中华民族');dbms_output.put('中国');dbms_output.put(',伟大的祖国');dbms_output.new_line;end;/伟大的中华民族中国,伟大的祖国1.4 new_line该过程用于在行的尾部追加行结束符。

当使用过程PUT时,必须调用NEW_LINE过程来结束行。

1.5 get_line和get_lines过程get_line用于取得缓冲区的单行信息,过程get_lines用于取得缓冲区的多行信息。

2 dbms_job作用:安排和管理作业队列,通过使用作业,可以使ORACLE数据库定期执行特定的任务。

2.1 submit用于建立一个新作业。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

oracle存储过程函数汇总()Character function return character valueThese functions all received is the character parameter type group (except CHR) and returns the character value?In addition to the special instructions, the function returnsVARCHAR2 most numerical types?The restrictions on the return type of the character function arethe same as those for the basic database type?The maximum value of character variable storage:The VARCHAR2 value is limited to 2000 characters (ORACLE 8 to 4000 characters)The CHAR value is limited to 255 characters (0RACLE8 2000)The long type is 2GBThe Clob type is 4GB1,CHRSyntax: Chr (x)Function: return in the database character set with numerical equivalence with the character of X. CHR and ASCII are a pair of inverse functions? After CHR conversion character after ASCII conversion and obtained the original wordFu.Use location: process and SQL statement?2,CONCATSyntax: CONCAT (stringl, string2)The function returns the stringl, and connected string2 behind.Use location: process and SQL statement?3,INITCAPSyntax: INITCAP (string)Function: returns the first letter of each word in the string, uppercase, and the other letter in the word, lowercase string. Theword is used? Spaces or alphanumeric characters to separate. It'snot letterCharacter unchanged.Use location: process and SQL statement?4,LTRIMSyntax: LTRIM (stringl, string2)Delete function: return counting from the left appears in the string2character in stringl. String2 is set to a single blank by default? The database will scan stringl, starting from the left. WhenWhen the first character in string2, the results will be returned? LTRIM,s behavior is very similar to that of RTRIM.Use location: process and SQL statement?5,NLS_INITCAPSyntax: NLS_INITCAP (stringt, nlsparams])Function: returns the string, the first letter of each wordcapitalized, and the other words in the word, lowercase string,nlsparamsThe different sequenee is different from the default value of thespecified session? If you do not specify a parameter, function andthe same INITCAP? Nlsparams can be used in the form of:'NLS_SORT二sort'Here sort made a sequence of language?Use location: process and SQL statement?Example:Select NLS INITCAP (,ABCD,) from dual;AbedAtSelect NLS_INITCAP ('abed') from dual;Abed6,NLS_LOWERSyntax: NLS_LOWER (string[, nlsparams])The function returns all the letters in the string are lowercasestring? Not alphabetic characters remain unchanged?The nlsparams Nlsparams parameter form and use and NLS_INITCAP are the same? If the nlsparams is not included, then the NLS_LOWER for processing and?Same LOWERUse position; process and SQL statement?7,NLS_UPPERSyntax: nls_upper (string[, nlsparams])Function: the return of all the letters in the string arecapitalized in the form of string? Not alphabetic characters remain unchanged? The parameters of nlsparams and NLS_INITCAP in the form and use of the same? IfNo set parameters, NLS_UPPER function and UPPER.& REPLACESyntax: REPLACE (string, search_str[, replace_str])Function: replace all substring search_str in string with optional replace_str, if no replace_str is specified, all substrings instringSearch_str will be deleted. REPLACE is a subset of TRANSLATE's functions set?Use location: process and SQL statement?9,RPADSyntax: RPAD (stringl, x[, string2])Function: return to insert a string2 character in the X characterin length on the location of string 1. If the length of the string2is less than X characters, according to the need for replication.If string2More than X characters, only the front of the stringl X of each character is used. If string2 is not specified, then use a space to "11. X is used to display the actual length of the string lengthratioBe long? The behavior of RPAD and LPAD is very similar, except that it is on the right and on the left is not filled?Example:Select RPAD ('123456789', 18,' abc') from dual;123456789abcabcabc10,RTRIMSyntax: RTRIM (stringl, [, string2]])Function: returns and deletes the character that appears in the stringl from the right? The string2. string2 is set to a single space by default? The database will scan stringl and start from the rightTo the first character in string2, the results will be returned tothe behavior of RTRIM and LTRIM are very similar?Use location: process and SQL statement.Example:Select RTRIM (T23456789'56789') from dual;One thousand two hundred and thirty-four11,SOUNDEXSyntax: SOUNDEX (string)Function: returns the sound representation of string? This is very helpful for comparing two words that are different in spelling butsimilar in pronunciationUse location: process and SQL statement?12,SUBSTRSyntax: SUBSTR (string, a[, b])Function: returns a substring of B that starts with the letterstring as the value a. If a is 0, then it is considered to startfrom the first character? If it is a positive number, the returncharacter is leftIf the B is negative, then the returned character is calculatedfrom the right end of the string from the right to the left?If B does not exist, then it defaults to the entire characterString. If B is less than 1, then NULL? will be returned? If a or B uses floating point numbers, the value is first converted to aninteger before the processing is performedUse location: process and SQL statement?13,TRANSLATESyntax: TRANSLATE (string, from_str, to_str)Function: return every character will appear in the from_str toreplace the corresponding characters in the to_str after the string? TRANSLATE is a superset of REPLACE,s functions?If from_str is Ionger than to_str, then the characters in from_strbut not in to_str will be deleted from string because they have no corresponding replacement characters? To_str cannot be emptyThe empty string that is.Oracle NULL, and if any of the parametersin TRANSLATE NULL, then the result is NULL?Use location: process and SQL statement?14,UPPERSyntax: UPPER (string)Function: returns uppercase string? is not letter character unchanged? If string is CHAR data type, then lhe result is alsoCHAR type. If string is VARCHAR2 type, thenThe result is also VARCHAR2 typeUsing location: procedural statements and SQL statements?Character function return numbetsThese functions accept character parameters and return numericresults? The parameter can be either CHAR or VARCHAR2? Although many of the actual results are integer values, the return resultsare simple NUMBERThe type, without any precision or scale definition?16,ASCIISyntax: ASCII (string)Function: the database character set returns the decimalrepresentation of the first byte of the string. Note that thefunction is still called ASCII. , although many character sets arenot 7 bits, and ASCII. CHR and ASCII are mutually exclusiveInstead, the function. CHR gets the response character of the given character encoding? ASCII gets the character encoding of the given characterUsing location: procedural statements and SQL statements.17,INSTRSyntax: INSTR (stringl, string2[a, b])Function: get the position of the string2 in string 1. Check fromthe left when stringl starts at a, and if a is a negative number,then stringl starts from the rightThe location of the B appears to be returned? Both a and B are set to 1 by default? This will return to the location of string2 forthe first time in string 1. If string2 is not available under the Aand B rulesFind, then the calculation of the return to the 0. position isrelative to the starting position of the stringl, regardless of thevalue of a and BUsing location: procedural statements and SQL statements?18,INSTRBSyntax: INSTRB (stringl, string2[a, [b]])Function: the same as INSTR, but the operation parameters of the character position is a byte?Using location: procedural statements and SQL statements?19,LENGTHSyntax: LENGTH (string)Function: the length of the byte unit that returns string? The .CHAR value is filled with the space type? If string is a data type CHAR, its ending spaces are computed to the middle of thestring lengthIf string is NULL, the return is NULL, instead of 0.Using location: procedural statements and SQL statements?20,LENGTHBSyntax: LENGTHB (string)Function: returns the length of string in bytes? For single byte character sets, LENGTHB and LENGTH are the sameUsing location: procedural statements and SQL statements?21,NLSSORTSyntax: NLSSORT (stringt, nlsparams])Function: get the string bytes used to sort string. All values areconverted to byte strings, so that consistency is maintainedbetween different databases. The role and function of NlsparamsNLS_INITCAP is the same? If you ignore the session parameters,using the default sort?Using location: procedural statements and SQL statements.The special function of dump Oracle (convert), several (substrb),lengthb (),()2011, 01 Friday, 14, 8:43 p. m.First, DUMP () functionDUMP (w[, x[, y[, z]]])[function] return data type, and the byte length in the internalstorage location.[parameters]W is a string of various types (such as character, numeric, date )X can be expressed as a return position, which can be: 8, 10, 16 or17, respectively: 8/10/16 and character, default is 10.Y and Z determine the position of the internal parameters[return] type <[length] >, index number 1 [bit / symbol, number 2,number 3,???,20]???Such as: Typ=2 Len二7: 60,89,67, 45, 23, 11102SELECT DUMP ('ABC', 1016) FROM dual;Results: Typ二96 Len二3 CharacterSet=ZlIS 16GBK: return 41,42,43 Code data type0 correspondence VARCHAR21 correspondence NUMBER8 correspondenee LONG12 correspondence DATE23correspondence RAW24correspond to LONG RAW69 correspondence ROWID96 correspondence CHAR106 correspondence MSSLABELYour meaning is as follows:1.types: type Number, Type=2 (the type of code can be found from the Oracle document)2.length: refers to the number of bytes stored3.symbol / index bitIn the memory, Oracle of positive and negative numbers were storage conversion:Positive: add 1 storage (to avoid Null)Negative number: reduced by 101, if the total length is less than21 bytes, and finally added a 102 (for sorting needs)Exponential scaling:Positive: index 二symbol / index - 193 (the highest is 1 is positive)Negative numbers: index 二62 - first byteFourStarting from < 1> > is a valid data bitFrom the beginning of "digital 1> is the highest effective bit, the numerical calculation method for storage:Add the results calculated below:Each digit number is multiplied by 10(T (index -N) (N is the sequential number of significant digits, N二0 of the first significant bit)5. ExamplesSQL> select dump (123456.789) from dual;Return: Typ二2 Len=6: 195,13,35,57, 79, 91<index >: 195-193 二 2<number 1> 13 - 1 = 12 *10(T (2-0) 120000<number 2> 35 - 1 二34 *10(T (2-1) 3400<digital 3> 57-1 二56 *10(T (2-2) 56<digital 4> 79-1 二78 *10(T (2-3).78<number 5> 91 - 1 = 90 *10(T (2—4).009One hundred and twenty-three thousand four hundred andfifty-six point seven eight nineSQL> select dump (-123456.789) from dual;Return: Typ二2 Len二7: 60,89,67,45, 23, 11102Algorithm:<index > 62 - 60 = 2 (the highest is 0, representing negative)<digital 1> 101-89 二12 *10(T (2-0) 120000<digital 2> 101-67 二34 *100° (2-1) 3400 < digital 3> 101-45 二56 *10(T (2-2) 56< digital 4> 101-23 二78 *100" (2-3). 78 < digital 5> 101-11 二90 *100° (2-4). 009123456. 789 (-)Now think about why adding 102 at the end is the need for sorting,and -123456? 789 is actually stored in the database60, 89, 67, 45, 23, 11-123456.78901 in the database for the actual storage60, 89, 67, 45, 23, 11,91Visible, if not added at the end of 102, in the sorting will appear-123456.789<-123456.78901 situation.Two, substrb functionSubstr and substrbPreviously known to have substrb, lengthb and other functions, butalso know that they are byte to calculate the length, not used, anddo not quite understand where to use them? Has been with substr, length, with the character to calculate the length, it seems to methat VARCHAR2 and char are inside the character, so naturally it is impossible for byte to calculate the unit length, will not usethese functions, but the fact that I was wrong? There is a procedure error, insert always reported to the table 1401 error,look at the program, feel very strange, the 50 is the error fieldof the target table length, insert corresponding to the fieldmethod is substr (1, 50 * *), what could go wrong? Some doubts arethe reason why Chinese characters are double byte, so try to change substr (* *, 1, 50) to substr (* *, 1, 25), and sure enough, ok.The Internet to find the reasons, find the answers in the asktom.The definition of the database in the VARCHAR2 and char is thelength of the field in two ways, in bytes or characters accordingto the leng th of the byte, by def in it ion is VARCHAR2 (n byte)or char (n byte), which is the default length of definition, thatis to say, we usually use VARCHAR2 (n) or char (n is defined bybyte length), according to the definition of the length of thecharacter is VARCHAR2 (n char) or char (n char), this definitioncan ensure that the field has sufficient space for the storage ofthe required character, whether these characters in length is thenumber of bytes? This is the cause of the error we encounter, the database character set is a multi byte character set, that is tosay Chinese characters accounted for more than one byte, and thesource field are Chinese, so substr (1, 50 * *) byte length mayreach 100, more than 50 natural target text in paragraph?To sum up some experience and lessons, think that before building a table, if a field needs to store Chinese, it is best to make surethat the length of the field is determined by the characters?If it is a character and the database character set is multi byte,then the table should be defined by the length defined by thecharacter to define the length of the field.How many bytes does a Chinese character have?According to coding form:GB231280 encoding is 2 bytes (Byte) contains 20902 Chinese characters, the encoding range is 0x8140-Oxfefe?GB18030-2000 (GBK2K) expands the Chinese characters on the basis of GBK, and increases the shape of Tibetan, Mongolian and other ethnic minorities? Is a variable length encoding, the second byte is compatible with GBK; four part is the extension of the byte font,bits, the encoding range is the first byte 0x81-Oxfe, two bytes of0x30-0x39, three bytes, four bytes of 0x30-0x39 0x81~0xfeUnicode range is generally used for \U0000-\UFFFF, for CJK EXT Barea Chinese characters, the scope is greater than \U20000UTF is divided into UTF-8/16/32 according to its basic length? Among them:UTF-8 is a variable length encoding, each Unicode code pointaccording to different ranges, you can have 1-3 bytes of differentlength?The length of UTFT6 is relatively fixed? As long as the character is not greater than \U200000, each Unicode code point uses 16 bits,i? e. 2 bytes, and exceeds the part using two UTF-16, i. e., 4bytes? According to the order of high and low byte, it is dividedinto UTF-16BE/UTF-16LE.The UTF-32 length is always fixed, and each Unicode code point is represented by 32 bits, 4 bytes? According to the order of high and low byte, it is divided into UTF-32BE/UTF-32LE.In general GB231280, so in most cases is 2 bytes?Technical experience of the differences between substrb and other functions due to different character setsIt has always been thought that English letters, numbers and otherspecial characters make up one byte, and Chinese characters make up two bytes? However, some mistakes have been made in the substrb used recently in Oracle database programmingThe substrb function is a string that intercepts a specific lengthin bytes? After I use it, I don,t get the desired result, becauseit's in the Chinese character stringAnd then I did the test:Substrb ('size abc', 1, 3) results: 'big'Substrb ('size abc', 1, 4) results: 'big' (containing a space)Substrb ('size abc,, 1, 5) results: 'big' (co ntaining two spaces)Substrb ('size abc,, 1,6) results: 'size' The above results suggestthat the database to a Chinese characters as three bytes? In the Forum on test results of other users is Chinese charactersaccounted for two bytes? I just know later, the database selectioncharacter set is UTF-8 form, the character set Chinese charactersfor more than two bytes will thus? The other on byte operationshould also function Chinese characters will have more questions,such as the lengthb function. It seems that after a lot ofattention.In addition, setting for the Chinese characters with the samestring processing function may have different results in differentcharacter sets? In the online search for the number of bytes onthe different character sets the custom Chinese characters whilesummary. Results there is no satisfactory answer, are veryfragmentary. After a time and then look for it.Three, convert () functionHow does Oracle SQL convert US7ASCII string encoding to utf8 orGB2312 encoding?Using CONVERT (char, dest char set,, source_char_set]) functionsWindows can modify theHKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_OraDblOg_homel nls_lang value directlySIMPLIFIED CHINESE_CHINA. ZHS16GBKOr use the convert functionSQL codeSQL> select CONVERT (datatype,? US7ASCIT ) fromBSTH_SYS_FIELD_ALIAS;CONVERT (DATATYPE,'US7ASCII') gfdfghdf? ?? ?SQL〉选择转换(数据类型的zhsl6gbk v)从bsth_sys_field_a.lias;(数据类型转换,‘zhsl6gbk”)gfdfghdf中文。

相关文档
最新文档