电脑技术学习

把SQL结果中几行值串起来的sum_string

dn001
把SQL结果中几行值串起来的函数sum_string:

示例如下:

CREATE OR REPLACE FUNCTION

sum_string (tablename IN VARCHAR2,fieldname IN VARCHAR2,wherecondistion IN VARCHAR2)

RETURN VARCHAR2 AS

tmpsql VARCHAR2(4000);

tmparray Dbms_Sql.Varchar2_Table;

retval VARCHAR2(4000) DEFAULT '';

BEGIN

tmpsql := 'select '||fieldname||' from '||tablename||' '||wherecondistion;

EXECUTE IMMEDIATE tmpsql BULK COLLECT INTO tmparray ;

IF(tmparray.Count=0) then

RETURN '';

END IF;

retval:=tmparray(1);

FOR i IN 2..tmparray.count LOOP

retval := retval||','||tmparray(i);

END LOOP;

RETURN retval;

END;

/

SELECT fn_constr('Tab','tname','') FROM dual;

SELECT fn_constr('Tab','tname','where tabtype = ''TABLE'' ') FROM dual;