今天遇到一个问题,要把SQL查出来的一列转化为字符串,如查询语句为:
select distinct c_fundacco from(
select c_custno from tconfirm tc where tc.c_agencyno='254'  and   tc.c_status='1'
   minus
select c_custno from tfundbrokerrelation tfb where tfb.c_relationtype='0')a,taccoinfo tf where a.c_custno=tf.c_custno。
结果为:
c_fundacco
541000082246
541000150815
541000249050
541000275745
。。。。。。
现在要把查询结果放到一个字符串v_fundaccos varchar2中,这样可以在存储过程错误提示中直接输出这个字符串。
raise_application_error(-20001,v_fundaccos);
第一想到的就是用游标,每次取出一行,然后累加到一个字符串变量中
,可是老大一看,就说这样会效率挺慢的,能不能不用游标用一个SQL语句实现。我第一的反应就是这不可能的,但是老大既然这么说了,还是得想办法啊。结果仔细一想,也不是不可能啊,按分组求和的思路可能可以写出来,把sql变一下:
select distinct c_fundacco,1 r from(
select c_custno from tconfirm tc where tc.c_agencyno='254'  and   tc.c_status='1'
   minus
select c_custno from tfundbrokerrelation tfb where tfb.c_relationtype='0')a,taccoinfo tf where a.c_custno=tf.c_custno
这样用r分组,还是有可能写出来的,心想,要是字符串也有一个像数值一样的sum就好了,这样按r分组,sum()一下就好了。
有问题还是找google,搜字符串相加 oracle,结果还真让我搜到了一个方便的函数可以解决这个问题。
这个函数为:SYS_CONNECT_BY_PATH
SYS_CONNECT_BY_PATH is valid only in hierarchical queries. It returns the path of a column value from root to node, with column values separated by char for each row returned by CONNECT BY condition.
用这个函数可以根据CONNECT BY条件把一列的值按‘父子’关系显示,父与子用字符分开,好了,这样我的问题就有解了:
select max(sys_connect_by_path(c_fundacco||chr(13)||chr(10),' ')v_fundaccos
  from (
    select distinct c_fundacco,1 r,rownum rn from(
     select c_custno from tconfirm tc where tc.c_agencyno='254'
         and tc.c_status='1'
      minus
      select c_custno from tfundbrokerrelation tfb
             where tfb.c_relationtype='0'
           )a,taccoinfo tf where a.c_custno=tf.c_custno
    )
  start  with  rn=1
  connect  by   prior rn=rn-1
  group by r
这里用
start with cond1
  connect by cond2 where cond3;
简单说来是将一个树状结构存储在一张表里,比如一个表中存在两个字段:
id,parentid那么通过表示每一条记录的parent是谁,就可以形成一个树状结构。
用上述语法的查询可以取得这棵树的所有记录。
其中COND1是根结点的限定语句,当然可以放宽限定条件,以取得多个根结点,实际就是多棵树。
COND2是连接条件,其中用PRIOR表示上一条记录,比如 CONNECT BY PRIOR ID=PRAENTID就是说上一条记录的ID是本条记录的PRAENTID,即本记录的父亲是上一条记录。
COND3是过滤条件,用于对返回的所有记录进行过滤。
rn为用oracle的伪列,这样我把根结点从一开始start  with  rn=1
prior rn=rn-1为上一条记录,再用r分组,就可以实现我的需求了。
   呵呵,看来Oracle的函数真是多阿,好多都没有用过,有时间再看看它的分析函数,这样写sql就简单多了