这部分的translate, start with...connect by prior, trim很新鲜,也有不好理解的地方。
--TBC 2016/10/22
--11.2.4 字符串处理函数
--1. 使用CONCAT函数合并字符串
SELECT CONCAT(CONCAT(ename, ' 的工作种类是:'), job) as "职别"
FROM emp
WHERE deptno = 20;
--转换成||操作符的语法:
SELECT ename || ' 的工作种类是:' || job as "职别"
FROM emp
WHERE deptno = 20;
--2. 使用SUBSTR进行字符截取
SELECT SUBSTR('ABCDEFG', 3, 4) "子串" FROM DUAL;
--指定负数参数
SELECT SUBSTR('ABCDEFG', -5, 4) "子串" FROM DUAL;
--SUBSTR在PL/SQL中的示例
DECLARE
v_str VARCHAR2(20):='Thisisastring';
BEGIN
DBMS_OUTPUT.PUT_LINE('SUBSTR(v_str,5,2):'||SUBSTR(v_str,5,2));
DBMS_OUTPUT.PUT_LINE('SUBSTR(v_str,-5,2):'||SUBSTR(v_str,-5,2));
DBMS_OUTPUT.PUT_LINE('SUBSTR(v_str,5,-2):'||SUBSTR(v_str,5,-2));
DBMS_OUTPUT.PUT_LINE('SUBSTR(v_str,5.23,2.34):'||SUBSTR(v_str,5.23,2.43));
END;
--3.使用LENGTH获取字符串长度
SELECT ename,LENGTH(ename) FROM emp WHERE deptno=20;
--4. 使用INSTR查找字串
SELECT INSTR('Oracle是一个关系型数据库系统,是一个数据库管理工具', '数据库') as "位置"
FROM DUAL;
--INSTR,指定开始位置和出现的次数
SELECT INSTR('Oracle是一个关系型数据库系统,是一个数据库管理工具',
'数据库',
6,
2) as "位置"
FROM DUAL;
--从右向左查询的示例
SELECT INSTR('Oracle是一个关系型数据库系统,是一个数据库管理工具',
'数据库',
-3,
1) as "位置"
FROM DUAL;
--5. 使用LPAD和RPAD填充字符串
SELECT RPAD(ename, 30, '.') as "右侧填充",
LPAD(sal, 8, '*') as "左侧填充"
FROM emp
WHERE deptno = 20;
--使用LPAD添加层次
--这个有点意思,但也不太好理解
SELECT LPAD('*', 2 * LEVEL - 1, '+') as "层次", LEVEL, ename
FROM emp
START WITH empno = 8091
CONNECT BY PRIOR mgr = empno;
select * from emp for update;
--6. 使用TRIM删除字符串2边的空白
SELECT TRIM(' This is a test ') as "简单TRIM语法" FROM dual;
--使用TRIM的各种参数实现截除
SELECT TRIM(LEADING FROM ' This is a test ') as "LEADING",
TRIM(TRAILING FROM ' This is a test ') as "TRAILING",
TRIM(BOTH FROM ' This is a test ') as "BOTH"
FROM dual;
--使用字符截除功能
--这个挺有用
SELECT TRIM('a' FROM 'aaaSCHOOLaaa') as "清除首尾字母a",
TRIM(LEADING 'a' FROM 'aaaSEARCHaaa') as "清除首部字母"
FROM dual;
--使用LTRIM和RTRIM进行多字符截除
SELECT LTRIM('isYour nameisis', 'is') as "LTRIM",
RTRIM('isYour nameisis', 'is') as "RTRIM",
LTRIM(RTRIM('isYour nameisis', 'is'), 'is') as "RTRIM和LTRIM"
FROM dual;
--使用REPLACE函数进行字符串替代
SELECT REPLACE('我有一帘幽梦', '一帘', '一地') as "指定替换字符",
REPLACE('我有一帘幽梦', '一帘') as "未指定替换字符"
FROM dual;
--使用TRANSLATE函数进行字符串替代
SELECT TRANSLATE('1tech23', '123', '456') as "替换1",
TRANSLATE('222tech', '2ec', '3it') as "替换2"
FROM dual;
--这部分不是很好理解
SELECT TRANSLATE('1tech23', 'My1tech23', 'Oracle') as "替换1",
TRANSLATE('222tech', 'This222tech', 'Oracle') as "替换2"
FROM dual;