字符串函数(Oracle)
本节介绍如下字符串函数:
LISTAGG
LISTAGG根据ORDER BY子句对每个组中的列值进行排序,并将排序后的结果拼接起来。
设置MigSupportForListAgg=false后,可迁移LISTAGG。
输入:LISTAGG
1 2 3 4 5 6 7 |
SELECT LISTAGG(BRANCH_ID, ',') WITHIN GROUP(ORDER BY AREA_ORDER) PRODUCTRANGE FROM (SELECT DISTINCT VB.BRANCH_ID, VB.VER_ID, VB.AREA_ORDER FROM SPMS_VERSION_BRANCH VB, SPMS_NODE_SET NS WHERE VB.BRANCH_TYPE IN ('1', '3') AND VB.AGENCY_BRANCH = NS.BRANCH_ID); |
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 |
SELECT LISTAGG (BRANCH_ID,',') WITHIN GROUP ( ORDER BY AREA_ORDER ) PRODUCTRANGE FROM ( SELECT DISTINCT VB.BRANCH_ID ,VB.VER_ID ,VB.AREA_ORDER FROM SPMS_VERSION_BRANCH VB ,SPMS_NODE_SET NS WHERE VB.BRANCH_TYPE IN ( '1','3') AND VB.AGENCY_BRANCH = NS.BRANCH_ID) ; |
STRAGG
STRAGG是一个字符串聚合函数,用于将多个行的值收集到一个用逗号分隔的字符串中。
输入:STRAGG
1 2 3 |
SELECT DEPTNO,ENAME,STRAGG(ename) over (partition by deptno order by ename RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS ENAME_STR FROM EMP; |
输出
1 2 3 4 5 6 |
SELECT DEPTNO,ENAME,STRING_AGG ( ename,',') over( partition BY deptno ORDER BY ename RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS ENAME_STR FROM EMP ; |
NVL2和REPLACE
“NVL2(表达式,值1,值2)”函数用于根据指定的表达式是否为空来确定查询返回的值。如果表达式不为Null,则NVL2返回“值1”。如果表达式为Null,则NVL2返回“值2”。
输入:NVL2
1
|
NVL2(Expr1, Expr2, Expr3) |
输出
1
|
DECODE(Expr1, NULL, Expr3, Expr2) |
REPLACE函数用于返回char,将所有search_string替换为replacement_string。如果将replacement_string省略或留空,则会删除所有出现的search_string。
在Oracle中,REPLACE函数有两个必选参数,一个可选参数。GaussDB(DWS)中的REPLACE函数有三个必选参数。
输入:嵌套的REPLACE
1 2 3 4 5 6 7 8 9 10 |
CREATE OR REPLACE FUNCTION F_REPLACE_COMMA ( IS_STR IN VARCHAR2 ) RETURN VARCHAR2 IS BEGIN IF IS_STR IS NULL THEN RETURN NULL ; ELSE RETURN REPLACE( REPLACE( IS_STR ,'a' ) ,CHR ( 10 ) ) ; END IF ; END F_REPLACE_COMMA ; / |
输出
1 2 3 4 5 6 7 8 9 10 |
CREATE OR REPLACE FUNCTION F_REPLACE_COMMA ( IS_STR IN VARCHAR2 ) RETURN VARCHAR2 IS BEGIN IF IS_STR IS NULL THEN RETURN NULL ; ELSE RETURN REPLACE( REPLACE( IS_STR ,'a' ,'' ) ,CHR ( 10 ) ,'' ) ; END IF ; end ; / |
输入:多个REPLACE
1 2 3 4 5 6 7 |
SELECT REPLACE( 'JACK and JUE' ,'J', '' ) "Changes" ,REPLACE( 'JACK1 and JUE' ,'J' ) "Changes1" ,REPLACE( 'JACK2 and JUE' ,'J' ) "Changes2" FROM DUAL ; |
输出
1 2 3 4 5 6 7 |
SELECT REPLACE( 'JACK and JUE' ,'J' ,'' ) "Changes" ,REPLACE( 'JACK1 and JUE' ,'J' ,'' ) "Changes1" ,REPLACE( 'JACK2 and JUE' ,'J' ,'' ) "Changes2" FROM DUAL ; |
输入:REPLACE,使用3个参数
1 2 3 4 5 |
SELECT REPLACE( '123tech123' ,'123', '1') FROM dual ; |
输出
1 2 3 4 5 |
SELECT REPLACE( '123tech123' ,'123' , '1' ) FROM dual ; |